How do you append a byte to a string in Go?
var ret string
var b byte
ret += b
invalid operation: ret += b (mismatched types string and byte)
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 few options:
// append byte as slice
ret += string([]byte{b})
// append byte as rune
ret += string(rune(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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With