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 关注
- 161 浏览
添加回答
举报