我對(duì) Go 很陌生,所以這可能很明顯。編譯器不允許以下代碼:(http://play.golang.org/p/3sTLguUG3l)package mainimport "fmt"type Card stringtype Hand []Cardfunc NewHand(cards []Card) Hand { hand := Hand(cards) return hand}func main() { value := []string{"a", "b", "c"} firstHand := NewHand(value) fmt.Println(firstHand)}錯(cuò)誤是: /tmp/sandbox089372356/main.go:15: cannot use value (type []string) as type []Card in argument to NewHand從規(guī)范來看,[]string 與 []Card 的底層類型不同,因此無法進(jìn)行類型轉(zhuǎn)換。確實(shí)如此,還是我錯(cuò)過了什么?如果是這樣,為什么會(huì)這樣?假設(shè),在一個(gè)非寵物示例程序中,我輸入了一段字符串,有沒有辦法將它“投射”到一張卡片中,或者我是否必須創(chuàng)建一個(gè)新結(jié)構(gòu)并將數(shù)據(jù)復(fù)制到其中? (我想避免這種情況,因?yàn)槲倚枰{(diào)用的函數(shù)會(huì)修改切片內(nèi)容)。
- 1 回答
- 0 關(guān)注
- 247 瀏覽
添加回答
舉報(bào)
0/150
提交
取消