1 回答

TA贡献1805条经验 获得超10个赞
定义一个接口
type Bin interface {
name() string
set([]byte) // maybe returning error
}
你将Bin只处理 s 。
type StructA struct { /* your code so far */ }
type StructB struct { /* your code so far */ }
func (a *StructA) set(b []byte) {
a.A = b[0]<<8 + b[1] // get that right, too lazy to code this for you
a.B = b[2]<<24 + b[3]<<16 + ...
}
// same for StructB
所以你的 StructA/B 现在是 Bins。
func makeBin(in myInput) Bin {
var bin Bin
if in.InputType == "a" {
bin = &StructA{}
} else {
bin = &StructB{}
}
bin.set(in.data) // error handling?
return bin
}
if如果您有两种以上的类型:如果一个或制作一个微型注册表(反映),请改用开关。
- 1 回答
- 0 关注
- 114 浏览
添加回答
举报