"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Does Go's Alias Type Conversion Create Copies?

Does Go's Alias Type Conversion Create Copies?

Published on 2024-12-21
Browse:404

Does Go's Alias Type Conversion Create Copies?

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3