在解码JSON时,我总是为每个对象明确地编写一个结构,这样我就可以为父结构中的单个对象实现Stringer接口,如下所示:
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)
}
Run Code Online (Sandbox Code Playgroud)
我最近了解到可以使用匿名结构进行嵌套.这种方法更简洁,用于定义要解码的数据的结构:
type Data struct {
Records []struct {
ID int
Value string
}
}
Run Code Online (Sandbox Code Playgroud)
但是,是否可以在结构的成员上定义一个方法,特别是一个匿名结构的成员?就像第一个代码块中的Stringer接口实现一样.