指针切片到一种类型切片到另一种类型切片之间的 Golang 类型转换

bn0*_*00d 1 casting type-conversion go protocol-buffers grpc

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

cannot use a.B (type []*C) as type []Z in field value
Run Code Online (Sandbox Code Playgroud)

代码:

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)
}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 5

使用for循环来转换切片中的每个值。别无退路

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