英文:
Golang struct issues to point parent struct method
问题
我在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()
方法中得到了这个错误?谢谢。
英文:
I have encountered a problem in Golang as bellow:
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())
}
Results:
> ./struct-2.go:33: bar.Foo.SetName("New value set to Foo struct name") used as value
But if I comment out this line then I can get the bar.Name()
method works.
// fmt.Println("Bar setName(): ", bar.SetName("New value set to Foo struct name") )
Why I got that error for bar.SetName()
method? Thanks.
答案1
得分: 1
<sub>回答问题,这样它就不会再出现在“未回答问题列表”中了。</sub>
您可以将_values_作为输入参数传递给其他函数。fmt.Println()
具有类型为interface{}
的可变参数。这意味着它接受任何类型的值,并且数量不限(传递的参数数量没有限制)。
(f *Foo) SetName()
没有返回值。如果您在*Foo
或*Bar
上调用此方法,它将不会产生任何返回值,因此您无法将其“返回值”传递给Println()
。
fmt.Println(bar.Name())
是可以的,因为Name()
返回一个string
类型的值。
英文:
<sub>Answering the question so it won't show up anymore in the "Unanswered questions list".</sub>
You may pass values to other functions as input parameters. fmt.Println()
has a variadic parameter of type interface{}
. This means it accepts values of any type, and in any number (no limit on the number of passed arguments).
(f *Foo) SetName()
has no return value. If you call this method either on a *Foo
or *Bar
, it will not produce any return values so you can't pass its "return value" to Println()
.
fmt.Println(bar.Name())
is OK because Name()
returns a value of type string
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论