本文共 1097 字,大约阅读时间需要 3 分钟。
对于结构体,有时候我们需要打印它的信息,但是打印出来是这样的:
type Family struct { Father string Mather string Brother string}func main() { f := Family{ "fa", "ma", "bro"} fmt.Println(f)}
输出:
{fa ma bro}并不是很直观,golang允许你通过实现 String() 接口来自定义输出。
type Family struct { Father string Mather string Brother string}func main() { f := Family{ "fa", "ma", "bro"} fmt.Println(f)}func (f Family) String() string { return "Father: " + f.Father + "\nMather: " + f.Mather + "\nBrother: " + f.Brother}
输出:
Father: fa Mather: ma Brother: bro或者使用引用的方式
type Family struct { Father string Mather string Brother string}func main() { f := &Family{ "fa", "ma", "bro"} fmt.Println(f)}func (f *Family) String() string { return "Father: " + f.Father + "\nMather: " + f.Mather + "\nBrother: " + f.Brother}
如果类型定义了 String() 方法,它会被用在 fmt.Printf() 中生成默认的输出:等同于使用格式化描述符 %v 产生的输出。还有 fmt.Print() 和 fmt.Println() 也会自动使用 String() 方法。
不要在 String() 方法里面调用涉及 String() 方法的方法,它会导致意料之外的错误,比如无限递归调用。
类似于这样:func (t TT) String() string { return fmt.Sprintf("%v", t)}
也很好理解,因为 fmt.Sprintf 又会去再次调用 String(),从而形成无限递归。
转载地址:http://jnaui.baihongyu.com/