The String Immutability Gotcha in Go

Go strings are immutable, so you must convert them to byte slices to modify their contents.

Go strings are immutable, meaning you cannot change their contents after creation; attempting to mutate a string via a pointer or byte slice conversion will either fail or create a new copy. In the Go fuzzing implementation, the TestStringImmutability test explicitly verifies that mutating a string value in a []any slice does not alter the original string's underlying bytes. To safely work with string data that needs modification, convert the string to a byte slice, modify the slice, and convert it back to a string if necessary.

func mutateString(s string) string {
    b := []byte(s) // Create a mutable copy
    b[0] = 'H'     // Modify the byte slice
    return string(b) // Convert back to string
}