Brendan Ang

Search

Search IconIcon to open search

Strings

Last updated Nov 8, 2022 Edit Source

# Strings

# Immutability

String assignment will not create a new copy of the string. Only string concatenation will create a new buffer for the string.

1
2
3
4
5
6
7
8
9
func main() { 
	x := "hello"
    y := x  
    // x and y share the same underlying memory 
    y += "world"  
    // now y uses a different buffer  
    // x still uses the same old buffer
    
}

Immutability means that individual characters or bytes cannot be reassigned directly.

1
2
3
4
5
6
7
func main() {  
	str := "hello"

	fmt.Println(str[1]) //101 (ascii of ā€˜eā€™)

	str[0] = 'a' //compile error
}

We can modify the string by creating a copy:

# Goroutine unsafety

# Runes

len(str) returns the number of bytes for the string. len(rune(str)) returns the actual number of characters.