我做了以下事情:
- 用 Display() fn 定义了一个“父”接口(interface)。
- 创建了 2 个实现各自 Display() fn 的子结构。
- 在 main() 中,创建了 2 个子对象并将它们添加到:
availableObjs[]interface{}
- 现在,在 For 循环中,想要获取对象并调用其各自的 Display() 函数。这就是令我震惊的地方。
GoPlayground 代码: https://play.golang.org/p/jdHpueokrEk
尝试在线搜索。
内联相同代码:
package main
import (
"fmt"
"reflect"
)
////// Parent Interface which has Display() fn.
type Parent interface {
Display()
}
// 2 Child structs implementing their Display() fn.
type Child1 struct {
name1 string
}
type Child2 struct {
name2 string
}
func (c1 Child1) Display() {
fmt.Println("c1Name : ", c1.name1)
}
func (c2 Child2) Display() {
fmt.Println("c2Name : ", c2.name2)
}
////////////////////////////////////////////
// Maintains the created objects
var availableObjs []interface{}
func main() {
//// Creating 2 objects
c1 := Child1{"Child1"}
c2 := Child2{"Child2"}
// Adding 2 objects to availableObjs
availableObjs = append(availableObjs, c1)
availableObjs = append(availableObjs, c2)
// Now, want to fetch the Object from Interface and call its respective Display() fn.
for _, obj := range availableObjs {
fmt.Println("")
fmt.Println("Obj Got = ",obj)
fmt.Println("Obj type = ",reflect.TypeOf(obj))
//obj.Display() // <-- Problem Line
}
}
需要做的事情:需要输入关于从数组接口(interface)获取对象后如何调用 Display() 函数的信息。
最佳答案
有两种方法可以做到这一点:一种是不使用空接口(interface),而是使用正确的父接口(interface)来声明 slice :
// Maintains the created objects
var availableObjs []Parent
请注意,Parent
接口(interface)的命名表明您正在使用继承概念来处理接口(interface),这不是我们在 Go 中使用的东西。您必须将界面更像是一种行为。在这种特殊情况下,您想要表示能够“显示”的事物的行为,因此您可以调用接口(interface) Displayer
。
这种命名约定,将 -er
附加到接口(interface)名称,是 Go 中非常常见的模式,即使有时您会得到一些奇怪的名称:)
从同样的意义上讲,Child
结构实际上并不是 Parent 接口(interface)的子级,它们只是隐式满足该接口(interface)的结构。
它们可以同时满足任意数量的接口(interface)。例如,如果他们有一个 String() 方法,他们也会满足 fmt.Stringer
接口(interface)。
现在,第二个选项是使用类型断言,使用 switch 语句或类型语句:
switch t := obj.(type) {
case Parent:
t.Display() // note that 't' is the new typed variable
}
或者
t, ok := obj.(Parent)
if ok {
t.Display()
}
请注意,上面的 ok
变量可以省略,但在这种情况下,如果类型断言不匹配,代码将崩溃。
关于function - 添加到 []interface{} 的对象。现在需要获取对象并调用对象各自的 Display() fn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56570184/