Why Go Does Not Allow Conversion of Slice Types (e.g. []Foo to []Bar)
Introduction
In Go, assigning one value to a variable of a different type is generally not allowed due to type safety and conversion rules. As you discovered, you cannot convert a slice of structures of one type (e.g. []Foo) to a slice of a different type (e.g. []Bar). This article aims to clarify why this conversion is not possible, even though the underlying types of Foo and Bar may be identical.
Conversion Rules
As per the Go specification, a non-constant value x can be converted to type T only if one of the following criteria is met:
Underlying Types of Slices
The underlying type of a slice is a pointer to the element type. For example, the underlying type of []Foo is []Foo, and the underlying type of []Bar is []Bar. Even though the underlying type of Foo is the same as the underlying type of Bar, this does not translate to identical underlying types for slices of Foo and Bar.
Reason for Non-Conversion
Therefore, the reason why Go does not allow conversion between slices of different element types, even if the underlying types are the same, is that the underlying types of the slices are not identical. As a result, a type conversion, such as []Bar(foos), is not permitted.
Alternative Solution
One possible solution to this issue is to define a custom type alias for a slice of Foo, such as Foos. This allows you to create a slice of Bars from a slice of Foos, as illustrated in the following code:
<code class="go">type Foo struct{ A int } type Foos []Foo type Bars Foos func main() { foos := []Foo{Foo{1}, Foo{2}} bars := Bars(foos) fmt.Println(bars) }</code>
In this case, the underlying types of Foos and Bars are identical, and the conversion works as expected.
Unsafe Package Considerations
While Go generally prohibits unsafe operations, it is possible to use the unsafe package to bypass the conversion restriction. However, this should be done with caution and understanding of potential consequences, as it can compromise type safety.
Conclusion
Understanding the conversion rules and underlying types of slices is crucial for handling type conversions in Go. While direct conversion between slices of different element types is not allowed, there are alternative solutions, such as defining custom type aliases, to achieve desired functionality while maintaining type safety.
The above is the detailed content of Why Can\'t I Convert a Slice of `Foo` to a Slice of `Bar` in Go?. For more information, please follow other related articles on the PHP Chinese website!