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.

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

报告相同问题?

悬赏问题

  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)