为什么在调用结构体的 fmt.Println 时,不使用成员的 String() 方法?

huangapple go评论101阅读模式
英文:

Why doesn't fmt.Println use String() methods of members when called on a struct?

问题

原始代码中的类型foo包含两个字段:bbb,它们都是指向bar类型的指针。在main函数中,我们创建了一个foo类型的实例f,并初始化了它的字段bbb

fmt.Println语句中,我们打印了ff.bf.bb的值。由于foo类型的String方法没有被定义,因此默认的打印格式是打印结构体的字段值。

对于f的打印结果,{[0x176f44] 0x176f44}表示f的字段bbb的内存地址。这是因为b是一个指向bar类型的指针切片,bb是一个指向bar类型的指针,它们的值是内存地址。

对于f.b的打印结果,[bar]表示f.b切片中的第一个元素的默认打印格式,即指向bar类型的指针的内存地址。

对于f.bb的打印结果,bar表示f.bb指针指向的bar类型的默认打印格式。

这种打印结果是由Go语言的默认打印格式决定的,它显示了字段的内存地址而不是字段的值。如果你想要打印字段的值而不是内存地址,你可以在foo类型上定义一个String方法,并在该方法中自定义打印格式。例如:

  1. func (f foo) String() string {
  2. return fmt.Sprintf("{[%v] %v} [%v] %v", f.b, f.bb, f.b[0], *f.bb)
  3. }

这样,打印结果将会是{[bar] bar} [bar] bar

英文:
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type bar struct {
  6. }
  7. func (b bar) String() string {
  8. return "bar"
  9. }
  10. type foo struct {
  11. b []*bar
  12. bb *bar
  13. }
  14. func main() {
  15. f := foo{b: []*bar{&bar{}}, bb:&bar{}}
  16. fmt.Println(f, f.b, f.bb)
  17. }

Why is the result

> {[0x176f44] 0x176f44} [bar] bar

and not

> {[bar] bar} [bar] bar

Are there any reasons behind it? It seems easy to implement and good for readability.

答案1

得分: 4

你的代码中有几个问题。你在bar上定义了String,但它是未导出的,你的字段也是未导出的。以下是修正后的代码:

  1. type Bar struct {
  2. }
  3. func (b Bar) String() string {
  4. return "bar"
  5. }
  6. type Foo struct {
  7. B []Bar
  8. BB Bar
  9. }
  10. func main() {
  11. f := Foo{B: []Bar{Bar{}}, BB: Bar{}}
  12. fmt.Println(f)
  13. }

这段代码也可以使用*Bar来实现。

英文:

You have several problems in your code. You define String on bar which is unexported, your fields are unexported as well. This works:

  1. type Bar struct {
  2. }
  3. func (b Bar) String() string {
  4. return "bar"
  5. }
  6. type foo struct {
  7. B []Bar
  8. BB Bar
  9. }
  10. func main() {
  11. f := foo{B: []Bar{Bar{}}, BB: Bar{}}
  12. fmt.Println(f)
  13. }

Playground: https://play.golang.org/p/OhoIcB7cA3.

This would also work with *Bar.

huangapple
  • 本文由 发表于 2017年3月16日 00:33:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/42815637.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定