💻 Tech
Under the hood, string in Go is actually a struct with two fields: a pointer to the underlying data and a length. When you pass a string value to a function, it’s passed by value; you can’t change the original string. This is why when you try to modify a character in a string, you get a panic, telling you that the string is non-addressable (i.e., it’s immutable). The question then would be: why is there a pointer to the underlying data if you can’t change it? The answer is that it’s there for efficiency. When you pass a string to a function, you’re not copying the underlying data, just the struct. This is why strings are efficient in Go. Imagine, two string variables have the same value “hello”. It would be performant if they refer to the same underlying data. However, if you change the the value of the other variable to another value, the pointer will then point to a different underlying data.
Reference: