Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在golang中使用类型断言进行强制转换_Go_Type Assertion - Fatal编程技术网

在golang中使用类型断言进行强制转换

在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...) } 游乐场:这个问题

我知道在go中使用类型断言实现了强制转换。 我试图对一个对象进行装箱,该对象是实现接口的结构的实例。 我的代码:

哪个输出:

[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...)
}