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

Casting using type assertion in golang

我了解到正在使用类型断言在 go 中实现转换。 我正在尝试对一个对象进行大小写处理,该对象是实现接口的结构的实例。 我的代码:

package main

import "fmt"

type Base interface {
    Merge(o Base)
}

type Impl struct {
    Names []string
}

func (i Impl) Merge (o Base) {
  other, _ := o.(Impl)
  i.Names = append(i.Names, other.Names...)
}

func main() {
    impl1 := &Impl{
        Names: []string{"name1"},
    }
    
    impl2 := &Impl{
        Names: []string{"name2"},
    }
    
    impl1.Merge(impl2)
    fmt.Println(impl1.Names)
}

输出这个:

[name1]

我希望输出为:

[name1, name2]

为什么这个转换不起作用?调试后似乎 other 变量为空。

您需要使用指针方法来修改接收器的构建。

func (i *Impl) Merge (o Base) {
  other, _ := o.(*Impl)
  i.Names = append(i.Names, other.Names...)
}

游乐场:https://play.golang.org/p/7NQQnfJ_G6A