目的:理解Golang *string
和string
的区别Golang中的*字符串和字符串之间有什么区别?
尝试
func passArguments() {
username := flag.String("user", "root", "Username for this server")
flag.Parse()
fmt.Printf("Your username is %q.", *username)
fmt.Printf("Your username is %q.", username)
}
结果:
Your username is "root".Your username is %!q(*string=0xc820072200)
但当*字符串被分配到一条条NG:
bla:=*username
fmt.Printf("Your username is %q.", bla)
它能够重新打印字符串:
Your username is "root".Your username is %!q(*string=0xc8200781f0).Your username is "root".
问题
- 为什么是*字符串=字符串,如!显示:
"root"
与%!q(*string=0xc8200781f0)
? - 在其他情况下,应该使用*字符串 而不是字符串,为什么?
- 为什么可以将 *字符串分配给字符串变量,而字符串显示不同,例如,显示:
"root"
与%!q(*string=0xc8200781f0)
?
变量有*标记是指针,或在存储器中的地址(把它看作当变量是房屋中的邮件地址)。有关更多信息,请参阅https://tour.golang.org/moretypes/1。 – ti7