For example,
package main
import "fmt"
func main() {
myString := "Hello there"
slice := make([]byte, 1, 1+len(myString))
slice[0] = byte(len(myString))
slice = append(slice, myString...)
fmt.Println(slice[0], string(slice[1:]))
}
Output:
11 Hello there
Answer from peterSO on Stack OverflowWe have an app that reads from a zmq PULL socket using goczmq. As we get data its of the format [][]byte.
The number of slices in the array is variable and also the size of each of the slice is variable.
I have a requirement to write it in a file and then read it back on. So I though of a file format where I write each slice as:
1-byte-slice length
4-byte-element-length
[variable size data]
4-byte-element-length
[variable size data] .... (end of first dataframe)
1-byte-slice length
4-byte-element-length
[variable size data]
4-byte-element-length
[variable size data]
I wrote a simple code that seems to do the job: https://go.dev/play/p/C1KU_G5DwKr
But I trying to figure out if there is a better way or am I reinventing the wheel and I could just use some library.
A slice whose underlying type is []byte, or a slice the underlying type of whose element type is byte.
package main
func main() {
type B byte
type BS []B
str := "hello"
bs := BS(str) // why is this ok,
str = string(bs) // but isn't this?
}gccgo thinks this is a legal program, but gc denies it.
For example,
package main
import "fmt"
func main() {
myString := "Hello there"
slice := make([]byte, 1, 1+len(myString))
slice[0] = byte(len(myString))
slice = append(slice, myString...)
fmt.Println(slice[0], string(slice[1:]))
}
Output:
11 Hello there
- First of all you need to initialize slice with
makefunction - To add data to slice you should use
appendfunction - To add elements from
[]byteto[]byteyou can use spread operator inappendcall. - And finally you need to use result of calling
appendfunction
https://play.golang.org/p/CP18akKsCa
Go embeds the string in the executable program as a string literal. It converts the string literal to a byte slice at runtime using the runtime.stringtoslicebyte function.
If you are initialising a []byte variable from a constant string, it looks like the compiler is smart enough not to create an intermediate string: instead, the backing array for the byte slice is initialised directly from static data rather than constructing a string variable first.
There is a data copy, but that is to be expected when constructing a mutable type.