Does Assigning Between Aliases Trigger Copying in Go?
Go allows the definition of custom types using aliases. Concerns arise regarding whether conversions between these alias types result in copies or merely structural changes.
Consider this example:
type MyString string var s = "very long string" var ms = MyString(s) var s2 = string(s) // Are ms or s2 a full copy of s?
Answer:
According to Go's conversion rules, non-constant conversions between numeric types or strings may incur a runtime cost due to representation changes. However, all other conversions, such as those between aliases, preserve the original representation without creating copies.
Therefore, both ms and s2 are not full copies of s but reference the same underlying value.
Impact on Function Calls:
When passing values to functions, copies are generally created. However, this does not hold true for alias types. Assigning an alias-typed value to a function parameter does not trigger copying:
func foo(s MyString){ ... } foo(ms) // No copy is made when passing ms to foo()
In summary, while conversions between alias types do not create copies of the underlying value, this principle does not extend to passing values to functions where copies are generally made.
The above is the detailed content of Does Go's Alias Type Conversion Create Copies?. For more information, please follow other related articles on the PHP Chinese website!