英文:
Issues with string and .String() in Golang
问题
我无法理解Go语言中的以下行为:
package main
import "fmt"
type Something string
func (a *Something) String() string {
return "Bye"
}
func main() {
a := Something("Hello")
fmt.Printf("%s\n", a)
fmt.Printf("%s\n", a.String())
}
输出结果为:
Hello
Bye
不知何故,这种行为感觉有点不一致。这是预期的行为吗?有人可以帮我解决这个问题吗?
英文:
I can't understand the following behaviour in Go:
package main
import "fmt"
type Something string
func (a *Something) String() string {
return "Bye"
}
func main() {
a := Something("Hello")
fmt.Printf("%s\n", a)
fmt.Printf("%s\n", a.String())
}
Will output:
Hello
Bye
Somehow this feels kinda incosistent. Is this expected behaviour?
Can someone help me out here?
答案1
得分: 4
你的String()
方法是在指针上定义的,但你却将一个值传递给了Printf
函数。
你可以选择将其改为:
func (s Something) String() string {
return "Bye"
}
或者使用:
fmt.Printf("%s\n", &a)
英文:
Your String()
is defined on the pointer but you're passing a value to Printf
.
Either change it to:
func (Something) String() string {
return "Bye"
}
or use
fmt.Printf("%s\n", &a)
答案2
得分: 1
参数类型不同。例如,
package main
import "fmt"
type Something string
func (a *Something) String() string {
return "Bye"
}
func main() {
a := Something("Hello")
fmt.Printf("%T %s\n", a, a)
fmt.Printf("%T %s\n", a.String(), a.String())
}
输出:
main.Something Hello
string Bye
英文:
The arguments types are different. For example,
package main
import "fmt"
type Something string
func (a *Something) String() string {
return "Bye"
}
func main() {
a := Something("Hello")
fmt.Printf("%T %s\n", a, a)
fmt.Printf("%T %s\n", a.String(), a.String())
}
Output:
main.Something Hello
string Bye
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论