Home >Backend Development >Golang >Does Go's Alias Type Conversion Create Data Copies?
Does Conversion Between Alias Types in Go Incur Copies?
In Go, custom types can be defined as aliases of existing types. When converting between an alias type and its underlying type, it's crucial to understand if a copy of the underlying value is made.
Answer:
As per the Go specification, converting to and from the underlying type of a custom type does not create a new copy of the data. This is because the conversion merely changes the type descriptor, without making any modifications to the actual value.
In the following example:
type MyString string var s = "very long string" var ms = MyString(s) var s2 = string(s)
Both ms and s2 are not full copies of s. They are only string structure copies, which reference the same underlying memory location. This is different from using []byte(s) to convert to a byte array, which would create a new copy of the data.
When passing an alias type value to a function:
func foo(s MyString){ ... } foo(ms(s))
The value is passed by value, so a copy of the string structure is created. However, this copy still references the same underlying string data as s. Therefore, changes made to s will also be visible within the function.
The above is the detailed content of Does Go's Alias Type Conversion Create Data Copies?. For more information, please follow other related articles on the PHP Chinese website!