我在 Golang 中遇到了如下问题:
package main
import "fmt"
type Foo struct {
name string
}
type Bar struct{
Foo
id string
}
func (f *Foo) SetName(name string) {
f.name = name
}
func (f *Foo) Name() string {
return f.name
}
func main(){
f := &Foo{}
f.SetName("Set Foo name")
fmt.Println("Get from Foo struct name: ", f.Name() )
bar := &Bar{
Foo:Foo{name: "Set Foo name from Bar struct!"},
id: "12345678",
}
fmt.Println("Bar setName(): ", bar.SetName("New value set to Foo struct name") )
fmt.Println("Bar getName(): ", bar.Name())
}
结果:
./struct-2.go:33: bar.Foo.SetName("New value set to Foo struct name") used as value
但是,如果我注释掉这一行,那么我可以让 bar.Name()
方法起作用。
// fmt.Println("Bar setName(): ", bar.SetName("New value set to Foo struct name") )
为什么我在 bar.SetName()
方法中遇到错误?谢谢。
最佳答案
回答问题,这样它就不会再出现在“未回答的问题列表”中。
您可以将值 作为输入参数传递给其他函数。 fmt.Println()
有一个类型为 interface{}
的可变参数。这意味着它接受任何类型和任何数量的值(对传递的参数数量没有限制)。
(f *Foo) SetName()
没有返回值。如果您在 *Foo
或 *Bar
上调用此方法,它将不会产生任何返回值,因此您无法将其“返回值”传递给 Println()
.
fmt.Println(bar.Name())
可以,因为 Name()
返回类型为 string
的值。
关于pointers - Golang 结构问题指向父结构方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27476503/