Calling method of named type

后端 未结 1 1452
既然无缘
既然无缘 2021-01-23 09:05

I have a named type, which I needed to make to do some JSON unmarshmaling:

type StartTime time.Time
func (st *StartTime) UnmarshalJSON(b []byte) error {...}
         


        
1条回答
  •  礼貌的吻别
    2021-01-23 09:17

    Using the type keyword you are creating a new type and as such it will not have the methods of the underlying type.

    Use embedding:

    type StartTime struct {
        time.Time
    }
    

    Quoting from the Spec: Struct types:

    A field or method f of an anonymous field in a struct x is called promoted if x.f is a legal selector that denotes that field or method f.

    So all the methods and fields of the embedded (anonymous) fields are promoted and can be referred to.

    Example using it:

    type StartTime struct {
        time.Time
    }
    
    func main() {
        s := StartTime{time.Now()}
        fmt.Println(s.Date())
    }
    

    Output (try it on the Go Playground):

    2009 November 10
    

    0 讨论(0)
提交回复
热议问题