Go结构体方法如何接收多种参数类型以避免代码重复
解决方案
方法一:基于公共接口实现(推荐,符合Go语言设计理念)
如果structType1和structType3存在共同的业务行为,先定义一个接口让两者实现,再将方法参数替换为该接口类型:
// 定义公共接口,包含两个结构体共有的业务方法 type InfoInterface interface { ExtractCoreData() string // 示例方法,根据实际业务逻辑调整 } // 让structType1实现接口 func (s structType1) ExtractCoreData() string { return s.CoreField // 假设structType1有对应字段 } // 让structType3实现接口 func (s structType3) ExtractCoreData() string { return s.KeyInfo // 假设structType3有对应字段 } // 修改原updateInfo方法 func (t *Worker) updateInfo(n InfoInterface, node structType2) { // 统一通过接口方法获取数据,后续逻辑复用 coreData := n.ExtractCoreData() // 执行通用业务逻辑... }
方法二:空接口+类型断言(适合无共同行为的场景)
如果两个结构体没有共用行为,仅需统一接收参数,可以用interface{}作为参数类型,在方法内部通过类型断言区分处理:
func (t *Worker) updateInfo(n interface{}, node structType2) { switch val := n.(type) { case structType1: // 处理structType1专属逻辑 processType1(val) case structType3: // 处理structType3专属逻辑 processType3(val) default: // 处理未知类型,可选择panic或返回错误 panic("unsupported parameter type for n") } // 执行通用业务逻辑... } // 可将专属逻辑抽为私有函数避免重复 func (t *Worker) processType1(s structType1) { // structType1的处理代码 } func (t *Worker) processType3(s structType3) { // structType3的处理代码 }
方法三:封装参数结构体(适合简单场景)
定义一个包含两种类型的结构体作为参数,通过标记字段区分传入类型:
type InfoParam struct { Type1 structType1 Type3 structType3 IsType1 bool // 标记当前传入的是structType1还是structType3 } func (t *Worker) updateInfo(n InfoParam, node structType2) { if n.IsType1 { // 处理structType1逻辑 handleType1(n.Type1) } else { // 处理structType3逻辑 handleType3(n.Type3) } // 通用逻辑... } // 调用示例 worker.updateInfo(InfoParam{Type1: structType1{}, IsType1: true}, nodeInstance) worker.updateInfo(InfoParam{Type3: structType3{}, IsType1: false}, nodeInstance)
内容的提问来源于stack exchange,提问作者drdot
相关产品推荐
相关产品推荐

