When working with alias types in Go, one may wonder if conversions between the alias and its underlying type result in copies. To explore this question, let's dissect an example:
type MyString string var s = "very long string" var ms = MyString(s) var s2 = string(ms)
Question: Are ms or s2 complete copies of s (like []byte(s) would be), or do they merely represent copies of the string structure (holding a pointer to the original value)?
Answer:
According to the Go specification on conversions, "all other conversions only change the type but not the representation of x." Therefore, converting to and from the underlying type of a custom type does not create a copy. In this case, ms and s2 are not copies of s but simply different representations of the same underlying value.
Passing Alias Types to Functions:
When passing an alias type to a function, a copy of the value is made. However, the copy will not actually create a new instance of the underlying value. For example:
func foo(s MyString) { ... } foo(ms(s)) // No copy is made here
Here, the copy that is passed to the function is of the MyString descriptor, not of the actual string that ms refers to.
The above is the detailed content of Go Alias Type Conversion: Does it Create Deep Copies of Underlying Data?. For more information, please follow other related articles on the PHP Chinese website!