Golang 类型在指向一种类型切片的指针切片与另一种类型切片之间的类型转换

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

我是 Golang 新手。
当我尝试它时,出现编译错误:

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

代码:

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

我想解决的方法是遍历切片并将其分配给另一个切片。但我知道一定有其他方法可以做到。

去游乐场:https://play.golang.org/p/v0PUTPh6Mt

使用for 循环转换切片中的每个值。别无他法

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