我有一些代码,打印消息“你好,欢迎来到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
的指针类型,或者它是某种方式?
先谢了。
2条答案
按热度按时间6qftjkof1#
声明了一个
func (*bytes.Buffer) String()
方法,所以fmt.Print()
使用它。fmt.打印“使用其操作数的默认格式进行格式化”。默认值遵循以下约定:如果值的类型定义了
String()
方法,则该方法将如何显示。详细信息与fmt.Stringer
接口类型有关。使用
fmt.Printf()
,您可以通过使用fmt.Printf("%p", &temp_buff)
获得您想要的内容。n3schb8v2#
在Go语言中,打印一个结构体会自动调用
String()
方法,即使它接收到一个指针类型,也会自动转换为值类型,并打印为字符串。这是与打印基元类型的区别。