英文:
Go fmt.Println display wrong contain
问题
我正在使用《Go之旅》学习Go语言。
这段代码非常简单,将名字的第一个和最后一个部分组合在一起,并在屏幕上输出。
运行代码后,输出的结果是一个十六进制地址,而不是"aaabbb"。有人可以帮我解决吗?谢谢。
package main
import "fmt"
type Name struct{
first,last string
}
func (name Name) fullName() string{
return (name.first + name.last)
}
func main(){
v := Name{"aaa","bbb"}
fmt.Println(v.fullName)
}
英文:
I am studying GO by using "a tour of go"<br>
The code is doing very simple things, combine first and last together and output on screen.<br>
The output is a hex address instead of "aaabbb" after I run the code. Could anyone can help me out? Thank you
package main
import "fmt"
type Name struct{
first,last string
}
func (name Name) fullName() string{
return (name.first + name.last)
}
func main(){
v := Name{"aaa","bbb"}
fmt.Println(v.fullName)
}
答案1
得分: 5
使用方法的结果
fmt.Println(v.fullName())
而不是方法的地址
fmt.Println(v.fullName)
例如,
package main
import "fmt"
type Name struct{
first,last string
}
func (name Name) fullName() string{
return (name.first + name.last)
}
func main(){
v := Name{"aaa","bbb"}
fmt.Println(v.fullName())
}
输出:
aaabbb
英文:
Use the result of the method
fmt.Println(v.fullName())
not the address of the method
fmt.Println(v.fullName)
For example,
package main
import "fmt"
type Name struct{
first,last string
}
func (name Name) fullName() string{
return (name.first + name.last)
}
func main(){
v := Name{"aaa","bbb"}
fmt.Println(v.fullName())
}
Output:
<pre>
aaabbb
</pre>
答案2
得分: 5
你没有调用函数fullName
,只是将“指针”传递给它:
参见这个链接:http://play.golang.org/p/GjibbfoyH0
package main
import "fmt"
type Name struct {
first, last string
}
func (name Name) fullName() string {
return (name.first + name.last)
}
func main() {
v := Name{"aaa", "bbb"}
fmt.Println(v.fullName())
}
英文:
You are not calling the function fullName
. you are just passing 'the pointer' to it:
see this http://play.golang.org/p/GjibbfoyH0
package main
import "fmt"
type Name struct {
first, last string
}
func (name Name) fullName() string {
return (name.first + name.last)
}
func main() {
v := Name{"aaa", "bbb"}
fmt.Println(v.fullName())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论