Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a byte to a string?

Tags:

go

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)
like image 423
Matt Joiner Avatar asked Mar 16 '15 02:03

Matt Joiner


3 Answers

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()
like image 78
Simon Whitehead Avatar answered Oct 27 '22 03:10

Simon Whitehead


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.

like image 32
Bayta Darell Avatar answered Oct 27 '22 05:10

Bayta Darell


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

like image 34
thomasrutter Avatar answered Oct 27 '22 05:10

thomasrutter