Rob*_*Min 2 syntax go go-interface
我是golang的新手.我需要设计一个函数来根据输入创建不同类型的对象.但我没有弄清楚如何设计界面.这是我的代码:
package main
import (
"fmt"
)
type AA struct{
name string
}
func (this *AA) say(){
fmt.Println("==========>AA")
}
type BB struct{
*AA
age int
}
func (this *BB) say(){
fmt.Println("==========>BB")
}
func ObjectFactory(type int) *AA {
if type ==1 {
return new(AA)
}else{
return new(BB)
}
}
func main() {
obj1 := ObjectFactory(0)
obj1.say()
obj2 := ObjectFactory(0)
obj2.say()
}
Run Code Online (Sandbox Code Playgroud)
无论我问ObjectFactory返回*AA还是接口{},编译器都会告诉我错误.我怎样才能使它工作?
首先,type在go中不允许使用变量名称(参见规范).那是你的第一个问题.
对象工厂的返回类型是*AA.这意味着它只能返回*AA类型的变量,这会导致BB类型的返回失败.如规范中所定义,go没有类型继承,只有struct embedding.
如果创建名为sayer的接口,则可以在ObjectFactory函数中使用该接口而不是*AA.
type sayer interface {
say()
}
Run Code Online (Sandbox Code Playgroud)
在尝试获取多个调度时,您可能希望使用此接口(如下面的代码所示(请参阅play.golang.org).
试试这段代码:
package main
import (
"fmt"
)
type sayer interface {
say()
}
type AA struct{
name string
}
func (this *AA) say(){
fmt.Println("==========>AA")
}
type BB struct{
*AA
age int
}
func (this *BB) say(){
fmt.Println("==========>BB")
}
func ObjectFactory(typeNum int) sayer {
if typeNum ==1 {
return new(AA)
}else{
return new(BB)
}
}
func main() {
obj1 := ObjectFactory(1)
obj1.say()
obj2 := ObjectFactory(0)
obj2.say()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2682 次 |
| 最近记录: |