Type Conversion Restrictions in Go
Go enforces strict typing rules, which can prevent seemingly obvious conversions between slices of different types containing the same underlying elements. This restriction is evident in the following code:
package main import "fmt" type Card string type Hand []Card func NewHand(cards []Card) Hand { hand := Hand(cards) return hand } func main() { value := []string{"a", "b", "c"} firstHand := NewHand(value) fmt.Println(firstHand) }
Despite the similarity between []string and []Card, the compiler reports an error:
cannot use value (type []string) as type []Card in argument to NewHand
Rationale
Go's specification prohibits this conversion to prevent accidental type conversions between unrelated types that coincidentally share the same structure.
Solutions
value := []string{"a", "b", "c"} cards := *(*[]Card)(unsafe.Pointer(&value)) firstHand := NewHand(cards)
The above is the detailed content of Why Can\'t I Directly Convert Between Slices of Different Types in Go?. For more information, please follow other related articles on the PHP Chinese website!