如何在 Go 中訪問自定義型別的原始函式?
我不相信這不是特定于 的gqlgen,但我的用例嚴重涉及他們的框架。我正在嘗試gqlgen按照此處的設定為日期構建自定義標量:https ://gqlgen.com/reference/scalars/
我在使用該MarshalGQL功能時遇到了困難。這是我到目前為止的代碼:
package scalars
import (
"fmt"
"io"
"time"
)
type Date time.Time
// UnmarshalGQL implements the graphql.Unmarshaler interface
func (date *Date) UnmarshalGQL(value interface{}) error {
dateAsString, ok := value.(string)
if !ok {
return fmt.Errorf("date must be a string")
}
parsedTime, err := time.Parse(time.RFC3339, dateAsString)
if err != nil {
return fmt.Errorf("failed to convert given date value (%s) to Time struct", dateAsString)
}
*date = Date(parsedTime)
return nil
}
// MarshalGQL implements the graphql.Marshaler interface
func (date Date) MarshalGQL(w io.Writer) {
// This line causes a compiler error
w.Write(date.Format(time.RFC3339))
}
我的問題是這一行:w.Write(date.Format(time.RFC3339))
它給了我這個編譯器錯誤:
date.Format undefined(型別Date沒有欄位或方法格式)編譯器(MissingFieldOrMethod)
我明白它為什么這么說。Date就編譯器所知,該型別只有兩個函式,UnmarshalGQL和MarshalGQL,這兩個函式都在這個檔案中宣告。我想獲得time.Time型別的函式,以便我可以格式化回傳的日期。我該怎么做呢?
uj5u.com熱心網友回復:
您可以按照 mkopriva 的建議進行顯式轉換Date然后time.Time格式化
或者您可以Date通過嵌入創建型別,time.time這將允許訪問time.Time格式方法
package main
import (
"fmt"
"io"
"time"
)
type Date struct {
time.Time
}
func (date *Date) UnmarshalGQL(value interface{}) error {
dateAsString, ok := value.(string)
if !ok {
return fmt.Errorf("date must be a string")
}
parsedTime, err := time.Parse(time.RFC3339, dateAsString)
if err != nil {
return fmt.Errorf("failed to convert given date value (%s) to Time struct", dateAsString)
}
*date = Date{parsedTime}
return nil
}
// MarshalGQL implements the graphql.Marshaler interface
func (date Date) MarshalGQL(w io.Writer) {
// This line causes a compiler error
w.Write([]byte(date.Format(time.RFC3339)))
}
func NewDate(v time.Time) *Date {
return &Date{v}
}
func main() {
}
操場
為了更多的理解,你可以閱讀golang-nuts討論這個的帖子
您“不能在非本地型別上定義新方法”,這是設計使然。
最佳實踐是將非本地型別嵌入到您自己的本地型別中,并對其進行擴展。型別別名(型別 MyFoo Foo)創建一個(或多或少)與原始型別完全不同的型別。我不知道使用型別斷言來解決這個問題的直接/最佳實踐方法。
彼得·布爾根
和:
型別的方法在定義它的包中。
這是邏輯上的連貫性。這是一種編譯美德。它被視為大型維護和多人開發專案的重要優勢。
但是,您所說的功能并沒有丟失,因為您可以如上所述將基本型別嵌入到新型別中,并添加任何您想要的內容,在您尋求的那種功能性“是”中,唯一需要注意的是你的新型別必須有一個新名稱,并且它的所有欄位和方法都必須在它的新包中。
邁克爾·瓊斯
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/505078.html
