16

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)

5 Answers 5

9

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()
Sign up to request clarification or add additional context in comments.

Comments

9

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.

Comments

5

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

Comments

0

Another solution in Golang.

package main

    import (
    
        "fmt"
    )
    
    func main() {
        byteArr := []byte{1,2,5,4}
        stringStr := "Test"
        output:= fmt.Sprintf("%v %v",byteArr,stringStr)
        fmt.Println("Output: ",output)
    }

Output

Output:  [1 2 5 4] Test

Comments

0

You can also use strings.Builder:

package main
import "strings"

func main() {
   var b strings.Builder
   b.WriteByte('!')
   println(b.String() == "!")
}

https://golang.org/pkg/strings#Builder.WriteByte

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.