目的:了解Golang中*string
和string
之间的区别。
尝试
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)
但当字符串被赋给一个字符串变量时:
bla:=*username
fmt.Printf("Your username is %q.", bla)
它能够再次打印字符串:
Your username is "root".Your username is %!q(*string=0xc8200781f0).Your username is "root".
问题
- 为什么 *string != string,例如显示:
"root"
vs.%!q(*string=0xc8200781f0)
? - 在什么其他情况下应该使用 *string 而不是 string,并说明原因?
- 为什么可以将 *string 分配给一个字符串变量,而字符串的显示不同,例如显示:
"root"
vs.%!q(*string=0xc8200781f0)
?