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 全志t113i启动qt应用程序提示internal error
  • ¥15 ensp可以看看嘛.
  • ¥80 51单片机C语言代码解决单片机为AT89C52是清翔单片机
  • ¥60 优博讯DT50高通安卓11系统刷完机自动进去fastboot模式
  • ¥15 minist数字识别
  • ¥15 在安装gym库的pygame时遇到问题,不知道如何解决
  • ¥20 uniapp中的webview 使用的是本地的vue页面,在模拟器上显示无法打开
  • ¥15 网上下载的3DMAX模型,不显示贴图怎么办
  • ¥15 关于#stm32#的问题:寻找一块开发版,作为智能化割草机的控制模块和树莓派主板相连,要求:最低可控制 3 个电机(两个驱动电机,1 个割草电机),其次可以与树莓派主板相连电机照片如下:
  • ¥15 潜在扩散模型的Unet特征提取