Go fmt.Println显示错误的内容

huangapple go评论83阅读模式
英文:

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 &quot;fmt&quot;

type Name struct{
	first,last string
}

func (name Name) fullName() string{
	return (name.first + name.last)
}

func main(){
	v := Name{&quot;aaa&quot;,&quot;bbb&quot;}
	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 &quot;fmt&quot;

type Name struct{
    first,last string
}

func (name Name) fullName() string{
    return (name.first + name.last)
}

func main(){
    v := Name{&quot;aaa&quot;,&quot;bbb&quot;}
    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 &quot;fmt&quot;

type Name struct {
	first, last string
}

func (name Name) fullName() string {
	return (name.first + name.last)
}

func main() {
	v := Name{&quot;aaa&quot;, &quot;bbb&quot;}
	fmt.Println(v.fullName())
}

huangapple
  • 本文由 发表于 2014年12月3日 04:29:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/27258358.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定