Home > Backend Development > Golang > Does Go's Alias Type Conversion Create Copies?

Does Go's Alias Type Conversion Create Copies?

DDD
Release: 2024-12-23 04:52:14
Original
732 people have browsed it

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?
Copy after login

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()
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template