7

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?
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Robert Zaremba
  • 8,081
  • 7
  • 47
  • 78
  • 4
    It helps to remember that *everything* in Go is a value, and all assignments are a copy of that value. `foo(ms(s))` does make a copy, but not because of the conversion. – JimB Aug 27 '15 at 15:51

1 Answers1

13

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.

icza
  • 389,944
  • 63
  • 907
  • 827