gotype-assertion

Casting using type assertion in golang


I understood that casting is being implemented in go using type assertion.

I'm trying to cast an object which is an instance of a struct that implements an interface.

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:

[name1, name2]

Why this casting doesn't work? After debugging this it seems like that the other variable is empty.


Solution

  • 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