How to Write Bytes to an Array in Go

In Go language, writing bytes to an array can be done using index assignment. Here is an example code snippet:

package main

import "fmt"

func main() {
    var arr [5]byte
    str := "Hello"

    for i := 0; i < len(str); i++ {
        arr[i] = str[i]
    }

    fmt.Println(arr)
}

In the code above, we declared a byte array arr with a length of 5, and then wrote each byte of the string “Hello” into the array sequentially. Finally, we printed the array, resulting in [72 101 108 108 111], which corresponds to the ASCII codes of the letters “H”, “e”, “l”, “l”, and “o”.

Please note that it is assumed here that the length of the array is sufficient to accommodate all the bytes of the string, otherwise it may cause an array out of bounds error.

bannerAds