Append a byte to a string?

In addition to ThunderCats answer.. you could initialize a bytes.Buffer from a string ... allowing you to continue appending bytes as you see fit:

buff := bytes.NewBufferString(ret)

// maybe buff.Grow(n) .. if you hit perf issues?

buff.WriteByte(b)
buff.WriteByte(b)

// ...

result := buff.String()

Here are a couple of options:

// append byte slice
ret += string([]byte{b})

// convert string to byte slice, append byte to slice, convert back to string
ret = string(append([]byte(ret), b))

Benchmark to see which one is best.

If you want to append more than one byte, then break the second option into multiple statements and append to the []byte:

buf := []byte(ret)    // convert string to byte slice
buf = append(buf, b)  // append byte to slice
buf = append(buf, b1) // append byte to slice
... etc
ret = string(buf)     // convert back to string

If you want to append the rune r, then it's a little simpler:

 ret += string(r)

Strings are immutable. The code above creates a new string that is a concatenation of the original string and a byte or rune.


It's a lot simpler than either of the other answers:

var ret string = "test"
var b byte = 'a'
ret += string(b)

// returns "testa"

That is, you can just cast an integer to a string and it will treat the integer as a rune (byte is an integer type). An then you can just concatenate the resulting string with +

Playground: https://play.golang.org/p/ktnUg70M-I

Tags:

Go