Go语言 为什么“&”号在传递给fmt.Print时不打印变量地址?

xe55xuns  于 2023-03-27  发布在  Go
关注(0)|答案(2)|浏览(159)

我有一些代码,打印消息“你好,欢迎来到2021年的教育”

package main

import (
  "fmt"
  "bytes"
)

func main() {
  // declaring variables of different datatypes
  var message string = "Hello and welcome to "
  var year int = 2021

  // temporary buffer
  var temp_buff bytes.Buffer

  // printing out the declared variables as a single string
  fmt.Fprintf(&temp_buff, "%s educative in %d",  message, year)

  fmt.Print(&temp_buff)
}

我希望最后一个fmt.Print将地址打印到temp_buff变量。为什么没有发生?我没有看到temp_buffer变量被定义为bytes.Buffer的指针类型,或者它是某种方式?
先谢了。

6qftjkof

6qftjkof1#

声明了一个func (*bytes.Buffer) String()方法,所以fmt.Print()使用它。
fmt.打印“使用其操作数的默认格式进行格式化”。默认值遵循以下约定:如果值的类型定义了String()方法,则该方法将如何显示。详细信息与fmt.Stringer接口类型有关。
使用fmt.Printf(),您可以通过使用fmt.Printf("%p", &temp_buff)获得您想要的内容。

n3schb8v

n3schb8v2#

在Go语言中,打印一个结构体会自动调用String()方法,即使它接收到一个指针类型,也会自动转换为值类型,并打印为字符串。这是与打印基元类型的区别。

相关问题