简体   繁体   English

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

[英]Casting using type assertion in golang

I understood that casting is being implemented in go using type assertion.我知道正在使用类型断言在 go 中实现强制转换。 I'm trying to case an object which is an instance of a struct that implements an interface.我正在尝试处理 object ,它是实现接口的结构的实例。 My Code:我的代码:

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

Which outputs this:哪个输出:

[name1]

I expect the output to be:我希望 output 是:

[name1, name2]

Why this casting doesn't work?为什么这个铸造不起作用? After debugging this it seems like that the other variable is empty.调试后,似乎other变量为空。

You need to use a pointer method to modify the receiver's build.您需要使用指针方法来修改接收器的构建。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM