【问题标题】:Golang type conversion between slice of pointers to slice of a type to slice of anotherGolang类型转换指针切片到一个类型的切片到另一个类型的切片
【发布时间】:2016-08-02 15:33:54
【问题描述】:

我是 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

【问题讨论】:

标签: go casting type-conversion protocol-buffers grpc


【解决方案1】:

使用for 循环转换切片中的每个值。没办法

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

【讨论】:

    猜你喜欢
    • 2016-05-25
    • 2019-07-18
    • 2013-10-23
    • 2011-12-03
    • 2012-11-25
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 2012-09-27
    相关资源
    最近更新 更多