Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does conversion between alias types in Go create copies?

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 (as it would be done with []byte(s))? Or they are just a string struct copies (which keeps the real value in a pointer)?

What if we are passing this to a function? E.g.:

func foo(s MyString){
  ...
}
foo(ms(s))  // do we copy s here?
like image 781
Robert Zaremba Avatar asked Aug 27 '15 15:08

Robert Zaremba


People also ask

What is type conversion in Go What does it do?

Type conversion is a way to convert a variable from one data type to another data type. For example, if you want to store a long value into a simple integer then you can type cast long to int. You can convert values from one type to another using the cast operator. Its syntax is as follows − type_name(expression)

Does Go support type conversion?

Still, the Go language is different, as it doesn't support an Automatic Type Conversion or Implicit Type Conversion even if the data types are compatible.

Does Golang have types?

It provides several built-in types such as string, bool, int and float64. Go supports composite types such as array, slice, map and channel. Composite types are made up of other types – built-in types and user-defined types.

Is type a keyword in Golang?

In Go, we can define new types by using the following form. In the syntax, type is a keyword.


1 Answers

Spec: Conversions:

Specific rules apply to (non-constant) conversions between numeric types or to and from a string type. These conversions may change the representation of x and incur a run-time cost. All other conversions only change the type but not the representation of x.

So converting to and from the underlying type of your custom type does not make a copy of it.

When you pass a value to a function or method, a copy is made and passed. If you pass a string to a function, only the structure describing the string will be copied and passed, since strings are immutable.

Same is true if you pass a slice (slices are also descriptors). Passing a slice will make a copy of the slice descriptor but it will refer to the same underlying array.

like image 93
icza Avatar answered Nov 15 '22 07:11

icza