Assigning byte to string location is not allowed

61 views
Skip to first unread message

Sathish VJ

unread,
Aug 13, 2020, 9:01:57 AM8/13/20
to golang-nuts
Why is this not allowed?

        s := "hello"
s[0] = 'a' // compile error: cannot assign to s[0]

Harald Weidner

unread,
Aug 13, 2020, 9:20:02 AM8/13/20
to Sathish VJ, golang-nuts
Hello,

> Why is this not allowed?
>
> s := "hello"
> s[0] = 'a' // compile error: cannot assign to s[0]

Because strings are immutable in Go. See https://golang.org/ref/spec#String_types

You can construct a new string, or convert to byte slive and back.

https://play.golang.org/p/0LvsxCCTM2G

Regards,
Harald

Jan Mercl

unread,
Aug 13, 2020, 9:20:10 AM8/13/20
to Sathish VJ, golang-nuts
Strings are immutable: once created, it is impossible to change the
contents of a string.
""""

(https://golang.org/ref/spec#String_types)

Sathish VJ

unread,
Aug 13, 2020, 9:24:38 AM8/13/20
to golang-nuts
Why would the design not allow the contents of the string to be changed?  I understand that the size and memory allocation for it is immutable.  

Brian Candler

unread,
Aug 13, 2020, 10:16:01 AM8/13/20
to golang-nuts
Immutable strings are a useful language feature.  For one thing, it makes them usable as map keys, without having to duplicate the entire contents.

A copy-by-value is cheap (it copies only the pointer and length):

   b := a

... but you know that there are never any issues around aliasing, e.g. if you pass a string to a function the caller will never see it mutate unexpectedly.  You can think of it as making string values behave the same as you'd expect from numeric values.

If you want a mutable string, look at []byte instead, and read the excellent intro to slices at https://blog.golang.org/slices

Kevin Chadwick

unread,
Aug 13, 2020, 10:35:26 AM8/13/20
to golang-nuts
On 2020-08-13 14:16, Brian Candler wrote:
>
> If you want a mutable string, look at []byte instead, and read the excellent
> intro to slices at https://blog.golang.org/slices
>

Also worth remembering that unicode strings aren't necessarily bytes, so
requiring verbose action for byte access, instead of using the strings package,
isn't really a bad thing.

Kevin Chadwick

unread,
Aug 13, 2020, 10:39:34 AM8/13/20
to golang-nuts
On 2020-08-13 14:16, Brian Candler wrote:
> If you want a mutable string, look at []byte instead, and read the excellent
> intro to slices at https://blog.golang.org/slices

Does anyone think the frontend languages can be persuaded to meet the web
standards and switch to Utf-8, rather than sticking to their Utf-16 bubble?

"https://github.com/dart-lang/sdk/issues/36316"
Reply all
Reply to author
Forward
0 new messages