在golang中使用类型断言进行强制转换
我知道在go中使用类型断言实现了强制转换。 我试图对一个对象进行装箱,该对象是实现接口的结构的实例。 我的代码: 哪个输出:在golang中使用类型断言进行强制转换,go,type-assertion,Go,Type Assertion,我知道在go中使用类型断言实现了强制转换。 我试图对一个对象进行装箱,该对象是实现接口的结构的实例。 我的代码: 哪个输出: [name1] 我预计产出为: [name1, name2] 为什么这个角色不起作用?调试后,似乎其他变量为空。您需要使用指针方法修改接收器的构建 func (i *Impl) Merge (o Base) { other, _ := o.(*Impl) i.Names = append(i.Names, other.Names...) } 游乐场:这个问题
[name1]
我预计产出为:
[name1, name2]
为什么这个角色不起作用?调试后,似乎
其他
变量为空。您需要使用指针方法修改接收器的构建
func (i *Impl) Merge (o Base) {
other, _ := o.(*Impl)
i.Names = append(i.Names, other.Names...)
}
游乐场:这个问题与类型断言或类型转换无关。您需要为
Merge
方法使用指针接收器。在您的实现中,Merge
接收接收器的副本并对其进行修改,因此永远不会修改main
中的副本。
func (i *Impl) Merge (o Base) {
other, _ := o.(*Impl)
i.Names = append(i.Names, other.Names...)
}