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.

图片转代码服务由CSDN问答提供 功能建议

解码JSON时,我总是为每个对象显式编写一个结构,以便为每个对象实现Stringer接口 父结构中的对象,如下所示:

  type数据结构{
记录[] Record 
} 
 
type记录结构{
 ID int 
值字符串 
} 
 
func(r记录)String()字符串{
 return fmt.Sprintf(“ {ID:%d Value:%s}”,r.ID,r.Value)
} 
 <  / code>  
 
 

我最近了解到可以对匿名结构进行嵌套。 此方法对于定义要解码的数据的结构更加简洁:

  type数据结构{
记录[]结构{
 ID int 
值字符串 
} 
} 
   
 
 

但是,是否可以在结构的成员(尤其是匿名结构的成员)上定义方法? 类似于第一个代码块中的Stringer接口实现。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题