为什么当“&”符号传递给fmt.Print时,它不会打印变量的地址?

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

Why does the "&" sign not print the variable address when passed to fmt.Print?

问题

我有一些代码,打印一条消息 "Hello and welcome to educative in 2021"。

  1. package main
  2. import (
  3. "fmt"
  4. "bytes"
  5. )
  6. func main() {
  7. // 声明不同数据类型的变量
  8. var message string = "Hello and welcome to "
  9. var year int = 2021
  10. // 临时缓冲区
  11. var temp_buff bytes.Buffer
  12. // 将声明的变量作为单个字符串打印出来
  13. fmt.Fprintf(&temp_buff, "%s educative in %d", message, year)
  14. fmt.Print(&temp_buff)
  15. }

我期望最后的 fmt.Print 打印出 temp_buff 变量的地址。为什么没有发生这种情况?我没有看到 temp_buffer 变量被定义为指向 bytes.Buffer 的指针类型,或者它是以某种方式定义的吗?

提前感谢。

英文:

I have some code, that print a message "Hello and welcome to educative in 2021"

  1. package main
  2. import (
  3. "fmt"
  4. "bytes"
  5. )
  6. func main() {
  7. // declaring variables of different datatypes
  8. var message string = "Hello and welcome to "
  9. var year int = 2021
  10. // temporary buffer
  11. var temp_buff bytes.Buffer
  12. // printing out the declared variables as a single string
  13. fmt.Fprintf(&temp_buff, "%s educative in %d", message, year)
  14. fmt.Print(&temp_buff)
  15. }

I expected the last fmt.Print to print the address to the temp_buff variable. Why is this not happening? I don't see the temp_buffer variable being defined as a pointer type to bytes.Buffer or is it somehow?

Thanks in advance.

答案1

得分: 4

有一个func (*bytes.Buffer) String() 方法被声明,所以fmt.Print()使用它。

fmt.Print "使用其操作数的默认格式进行格式化"。默认情况下,如果值的类型定义了一个String()方法,那么该方法将用于显示该值。这些细节与fmt.Stringer接口类型有关。

通过使用fmt.Printf("%p", &temp_buff),你可以得到你想要的结果。

英文:

There is a func (*bytes.Buffer) String() method declared, so fmt.Print() uses it.

fmt.Print "formats using the default formats for its operands". The defaults follow the convention that if the type of the value defines a String() method, then that method is how it will be displayed. The details are related to the fmt.Stringer interface type.

With fmt.Printf() you can get what you want, by using a fmt.Printf("%p", &temp_buff).

答案2

得分: 3

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

英文:

In Go, printing a structure will automatically call the String() method, even if it receives a pointer type, it will be automatically converted to a value type and printed as a string. This is the difference from printing primitive types.

huangapple
  • 本文由 发表于 2023年3月22日 08:45:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75807558.html
匿名

发表评论

匿名网友

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

确定