Home >Backend Development >Golang >How Can I Safely Convert a Slice of Strings to a Slice of Custom Types in Go?
Type Conversion: Strings to Custom Types
In Go, converting a slice of strings into a slice of custom types can be challenging. Consider the following example:
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) }
This code will result in a compiler error:
cannot use value (type []string) as type []Card in argument to NewHand
The reason for this error lies in the specification design decision to prevent accidental conversions between unrelated types that coincidentally share the same structure. However, under certain circumstances, it may be necessary to convert between such slices.
Unsafe Conversion
While it is not technically impossible to convert between slices with identical underlying types, the safe approach involves copying the slice. Nevertheless, it is possible to perform a direct conversion (without copying) using the unsafe package:
value := []string{"a", "b", "c"} // convert &value (type *[]string) to *[]Card via unsafe.Pointer, then deref cards := *(*[]Card)(unsafe.Pointer(&value)) firstHand := NewHand(cards)
Caution
Using the unsafe package requires extreme caution as it allows programs to bypass the type system and access arbitrary memory. If the conversion is crucial, it is advisable to consider other options, such as defining a new type that encapsulates both the string and card types and performing a safe conversion within that structure.
The above is the detailed content of How Can I Safely Convert a Slice of Strings to a Slice of Custom Types in Go?. For more information, please follow other related articles on the PHP Chinese website!