gocastingtype-conversionprotocol-buffersgrpc

Golang type conversion between slice of pointers to slice of a type to slice of another


I am new to Golang.
When I try it I get a compile error:

cannot use a.B (type []*C) as type []Z in field value

Code:

package main

type A struct {
    B []*C
}

type C struct {
    char string
}

type X struct {
    Y []Z
}

type Z struct {
    char string
}

func doSomething(r interface{}) X {
    a := r.(*A)
    return X{
        Y: a.B, // cannot use a.B (type []*C) as type []Z in field value
    }
}

func main() {
    something := &C{"abc"}
    somewhere := A{}
    somewhere.B = []*C{something}

    doSomething(somewhere)
}

The way I am thinking of getting around is by iterating over the slice and assigning it to another. But I know there must be other ways to do it.

Go playground: https://play.golang.org/p/v0PUTPh6Mt


Solution

  • use for loop for convert each value in slice. no other way

    https://play.golang.org/p/oQi6oVz6My