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

Does Go's Alias Type Conversion Create Data Copies?

Susan Sarandon
Release: 2024-12-26 10:44:10
Original
842 people have browsed it

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template