-1

How do I convert a single byte to a slice of bytes in Go?

I have tried this in a few different ways however none of them have worked. I keep getting an error stating: cannot convert charBytes[i] (type byte) to type []byte.

The only working method I have found for this so far is to get a character from a string, cast it as a string then recast it as a byte array.

characters := "some text"    
for i := 0; len(characters); i++ {    
    var b []byte = []byte(string(characters[i]))    
    fmt.Println(b)
}
3
  • from the error, it looks like you already have a slice? Why not just slice that?
    – JimB
    Jan 26, 2021 at 20:42
  • I'm calling a method that requires slices however I have a byte. I need a slice to call the method. Jan 26, 2021 at 20:44
  • 1
    This will not work with special characters. What are you actually trying to do? What method do you want to call?
    – TehSphinX
    Jan 26, 2021 at 21:49

2 Answers 2

5

Spec: Conversions does not allow to convert a byte to []byte. You may however create a slice that contains that single byte:

var value byte

data := []byte{value}

Also note that in your case to obtain a slice that contains the ith byte, simply use a slice expression:

characters[i:i+1]

Also don't forget that indexing a string indexes its UTF-8 byte sequence, and not the runes of the string, which does make a difference if the string contains runes that are encoded to multiple bytes (in UTF-8).

If you do want to iterate over the runes instead of the bytes, you could use a for .. range, or you could convert the input string to []rune first.

1

This seems to be what you're actually trying to do:

    characters := "some text"
    for i := 0; i < len(characters); i++ {
        b := characters[i]
        fmt.Println(b)
    }

Your code is confusing (and doesn't compile), but you appear to want to iterate over the string, and for the element you are currently on, convert the character to a byte and print it. If so, you don't need (or want) to convert anything to a []byte.


If you don't want to iterate byte by byte but instead character by character, use a range loop. It iterates over runes:

    characters := "søme spécial text"
    for _, r := range characters {
        char := string(r)
        b := []byte(char)
        fmt.Println(char, b)
    }
3
  • 1
    characters[i] is already of type byte. No need to convert it or specify the type of b.
    – TehSphinX
    Jan 26, 2021 at 21:46
  • 1
    Also this solution is completely ignoring all characters outside the ASCII space. Although that might mostly be due to the same problem in the question.
    – TehSphinX
    Jan 26, 2021 at 21:47
  • @TehSphinX Thanks! I'm super tired and wasn't paying enough attention when updating the OP's code. Updated. Jan 26, 2021 at 22:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.