小编BeM*_*her的帖子

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

在解码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接口实现一样.

struct types nested anonymous go

5
推荐指数
1
解决办法
190
查看次数

标签 统计

anonymous ×1

go ×1

nested ×1

struct ×1

types ×1