-3
var a byte
var b []byte
i know how to do this
c := append(b,a...)

but how do i do this elegantly?

c := append(a,b...) <-- what's the solution does anyone knows?

Would like to have the c[0] == a, c[1:] == b for checking next time

2
  • 1
    You cannot append to arrays in Go. Arrays are fixed-length. But you don't have an array, you have a slice. Commented Jun 13, 2020 at 7:42
  • 1
    Beyond that, what you have is already pretty elegant. What are you hoping to improve? Commented Jun 13, 2020 at 7:52

2 Answers 2

2

You can make a a slice as well then append it with b.

c := append([]byte{a}, b...)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the bytes.Buffer to make this cleaner:

var a byte
var buf bytes.Buffer

buf.WriteByte(a)// For a single byte
buf.Write([]byte{a})// For byte slice

2 Comments

Why bytes.buffer? is it slower or faster?
It is a handy wrapper around byte slice, and also it implements several interfaces, io.Reader, io.Writer to name a few. It is an ideal choice when you have a lot of values to append, and also it provides methods for efficient conversion of byte slice to string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.