3 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超10個(gè)贊
重要的是相同的界面:
package main
import (
"fmt"
)
type Item interface{
fmt.Stringer
}
type ItemA struct {
}
func (a ItemA) String() string {
return "item A"
}
type ItemB struct {
}
func (a ItemB) String() string {
return "item B"
}
func main() {
items := make([]Item, 0)
items = append(items, ItemA{}, ItemB{})
fmt.Printf("Items: %v", items)
}

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
您似乎期待的是.Go 不支持非接口類型的動(dòng)態(tài)綁定。因此,您可以使用接口subtype polymorphism
package main
func main(){
var bar Bar
var foo Foo
foo.Symbols = append(foo.Symbols, bar)
}
type Symbol interface {
Symbol()
}
type Base struct {
a int32
}
func (b Base)Symbol(){}
type Foo struct {
Base
b int32
Symbols []Symbol
}
type Bar struct {
Base
c int32
}
或者,如果您不喜歡使用界面,則可以使用如下所示的技巧來反映。
package main
import "fmt"
func main(){
var bar Bar
var foo Foo
err := foo.AddSymbol(bar)
if err != nil{
fmt.Println(err)
}
}
type Base struct {
a int32
}
func (b Base)Symbol(){}
type Foo struct {
Base
b int32
symbol []interface{} // field made private
}
// AddSymbol : helper to append values
func (f *Foo)AddSymbol(in interface{})(err error){
if f.symbol == nil{
f.symbol = make([]interface{},0)
}
switch typ := in.(type) {
case Base,Bar,Foo:
f.symbol = append(f.symbol,in)
default:
return fmt.Errorf("provided type: %s is not supported",typ)
}
return nil
}
type Bar struct {
Base
c int32
}

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
我做了一些搜索和閱讀。我想要實(shí)現(xiàn)的目標(biāo)需要所謂的“總和類型”。目前 Go 不支持總和類型。但是,很少有替代方法來模擬求和類型的行為。它們?cè)谶@里得到了很好的描述 Go 中求和類型的替代方案。
更重要的是,看起來總和類型可能會(huì)在Go 2中得到支持。進(jìn)一步閱讀建議:規(guī)范:添加總和類型/可區(qū)分的并集,規(guī)范:泛型:使用類型集刪除約束中的類型關(guān)鍵字。
- 3 回答
- 0 關(guān)注
- 110 瀏覽
添加回答
舉報(bào)