如何在Go语言类型断言分支中修改结构体字段?
问题解决:Go语言中修改不同结构体字段的方法
你的代码无法修改原结构体字段的核心原因是:结构体是值类型,传入interface{}时会生成副本,你修改的只是副本而非原结构体。以下是两种可行的解决方案:
方案一:通过指针类型匹配修改
直接修改encryptId函数,让它接收指针类型并在分支中处理指针,这样就能直接操作原结构体的字段:
修正后的encryptId函数
func encryptId(in interface{}) { switch v := in.(type) { case *cloth: v.clothId = encryption(v.clothId, "cloth") case *pants: v.pantsId = encryption(v.pantsId, "pants") default: return } }
对应的main函数调用
需要传入结构体的指针:
func main() { clo := cloth{"cloth", "blue"} pan := pants{"pants", "green"} encryptId(&clo) encryptId(&pan) fmt.Println(clo) fmt.Println(pan) }
方案二:定义统一接口(更符合Go语言设计)
通过定义接口规范,让所有商品结构体实现该接口,扩展性更强,后续新增商品类型无需修改encryptId函数:
定义Item接口
type Item interface { EncryptId() }
让结构体实现接口
为cloth和pants分别实现EncryptId方法:
func (c *cloth) EncryptId() { c.clothId = encryption(c.clothId, "cloth") } func (p *pants) EncryptId() { p.pantsId = encryption(p.pantsId, "pants") }
简化encryptId函数
func encryptId(in Item) { in.EncryptId() }
调用方式(同样传入指针)
func main() { clo := cloth{"cloth", "blue"} pan := pants{"pants", "green"} encryptId(&clo) encryptId(&pan) fmt.Println(clo) fmt.Println(pan) }
两种方案执行后,都会输出你期望的结果:
{clothcloth blue}
{pantspants green}
内容的提问来源于stack exchange,提问作者bread
相关产品推荐
相关产品推荐

