dqpc1845 2013-01-01 13:29
浏览 117
已采纳

由类型文字定义的类型的struct字段上的方法

When decoding JSON I've always explicitly written a struct for each object so that I could implement the Stringer interface for individual objects in a parent struct like so:

type Data struct {
    Records []Record
}

type Record struct {
    ID int
    Value string
}

func (r Record) String() string {
    return fmt.Sprintf("{ID:%d Value:%s}", r.ID, r.Value)
}

I recently learned that it is possible to do nesting with anonymous structs. This method is much more concise for defining the structure of the data to be decoded:

type Data struct {
    Records []struct {
        ID int
        Value string
    }
}

But, is it possible to define a method on a member of a struct, particularly a member which is an anonymous struct? Like the Stringer interface implementation in the first code block.

  • 写回答

1条回答 默认 最新

  • doutizhou5312 2013-01-01 13:40
    关注

    No, methods can be attached only to named types defined in the same package. From the specs:

     A method is a function with a receiver. A method declaration binds an identifier, the method name, to a method. It also associates the method with the receiver's base type.

    MethodDecl   = "func" Receiver MethodName Signature [ Body ] .
    Receiver     = "(" [ identifier ] [ "*" ] BaseTypeName ")" .
    BaseTypeName = identifier .
    

    The receiver type must be of the form T or *T where T is a type name. The type denoted by T is called the receiver base type; it must not be a pointer or interface type and it must be declared in the same package as the method. The method is said to be bound to the base type and the method name is visible only within selectors for that type.

    The type of the Records field in the second OP example is defined using a type literal, ie. the 'type name' condition above is not met.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?