英文:
Why does the "&" sign not print the variable address when passed to fmt.Print?
问题
我有一些代码,打印一条消息 "Hello and welcome to educative in 2021"。
package main
import (
"fmt"
"bytes"
)
func main() {
// 声明不同数据类型的变量
var message string = "Hello and welcome to "
var year int = 2021
// 临时缓冲区
var temp_buff bytes.Buffer
// 将声明的变量作为单个字符串打印出来
fmt.Fprintf(&temp_buff, "%s educative in %d", message, year)
fmt.Print(&temp_buff)
}
我期望最后的 fmt.Print
打印出 temp_buff 变量的地址。为什么没有发生这种情况?我没有看到 temp_buffer 变量被定义为指向 bytes.Buffer
的指针类型,或者它是以某种方式定义的吗?
提前感谢。
英文:
I have some code, that print a message "Hello and welcome to educative in 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)
}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论