[英]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
循環以轉換切片中的每個值。 別無退路
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.