doujiu8826 2018-10-29 14:48
浏览 59
已采纳

为什么%v为嵌套结构打印出意外的值?

When printing a struct with nested struct which has a String() implemented, the %v format prints an 'unexpected' value per our understanding.

Below is the code snippet.

package main

import (
  "fmt"
)

type Inner struct {
}

type A struct {
    Inner
    FieldA string
}

func (i Inner) String() string {
    return "anything"
}

func main() {
    myA := A{FieldA: "A"}
    fmt.Printf("%v", myA)
}

We expect the output to be

{anything A}

But the actual result is

anything

Why this result? It seems FieldA is ignored? To make it more confusing, if we have two nested structs where both of them have String() implemented, the output is expected.

package main

import (
  "fmt"
)

type Inner struct {
}

type InnerAgain struct {
}

type A struct {
    Inner
    InnerAgain
    FieldA string
}

func (i Inner) String() string {
    return "anything"
}

func (i InnerAgain) String() string {
    return "nothing"
}

func main() {
    myA := A{FieldA: "A"}
    fmt.Printf("%v", myA)
}

The output is

{anything nothing A}

...

  • 写回答

2条回答 默认 最新

  • duanchui1279 2018-10-29 14:52
    关注

    Since you are embedding Inner, you inherent all its properties - including the String() - function. So %v is actually calling Inner.String()

    From the docs (https://golang.org/pkg/fmt/) :

    1. If an operand implements method String() string, that method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 CATIA有些零件打开直接单机确定终止
  • ¥15 请问有会的吗,用MATLAB做
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址