3 回答

TA貢獻1868條經驗 獲得超4個贊
為這兩種類型聲明一個具有通用功能的接口。使用接口類型作為參數類型。
// Der gets d values.
type Der interface {
D() string
}
type Thing struct {
a int
b int
c string
d string
}
func (t Thing) D() string { return t.d }
type OtherThing struct {
e int
f int
c string
d string
}
func (t OtherThing) D() string { return t.d }
func doSomething(t Der) error {
fmt.Println(t.D())
return nil
}

TA貢獻1866條經驗 獲得超5個贊
您可以通過從基本結構組合它們來為兩個結構提供一些共享功能:
package main
import (
"fmt"
)
// Der gets d values.
type Der interface {
D() string
}
type DBase struct {
d string
}
func (t DBase) D() string { return t.d }
type Thing struct {
DBase
a int
b int
c string
}
type OtherThing struct {
DBase
e int
f int
c string
}
func doSomething(t Der) error {
fmt.Println(t.D())
return nil
}
func main() {
doSomething(Thing{DBase: DBase{"hello"}})
doSomething(OtherThing{DBase: DBase{"world"}})
}
DBase為 和提供字段 ( d) 并以Der相同的方式滿足接口。它確實使結構文字的定義時間更長。ThingOtherThing
- 3 回答
- 0 關注
- 160 瀏覽
添加回答
舉報