pointers - Golang 结构问题指向父结构方法

标签 pointers go struct return-value embedding

我在 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/

相关文章:

c - 如何获得与出现次数相对应的字母进行排序?

c - "softlink between 2 pointers in C"这可能吗,在字符串排序中需要这个

go - 将文件用作 Stdin (Golang) 时在第二次提示时获取 EOF

recursion - 从路径字符串中获取树状结构

go - 为什么详细给出的GO语言程序中的接口(interface)字段访问有效?

python - 如何遍历和搜索 python 字典?

c - Qsort() 不适用于结构

C++:如何将具有指针的类保存为文件中的成员?

c++全局定义和初始化结构

c - 如何在c中比较两个无符号整数(uint8_t)