What is the difference between []byte() and []byte{}?

i was just trying about byte and i noticed a strange behaviour or may be i don’t fully understand it:
b := []byte{‘2’, ‘3’}
fmt.Println(b) // this print [50 51]
e := []byte(‘2’)
fmt.Println(e) // err: cannot convert ‘2’ rune to type []byte
so my conclusion is:
[]byte{} is a slice of byte that takes in only positive numbers while
[]byte() is a slice of byte that takes in only strings
mean while all this does is type conversion which convert int or string to uint8 (fmt.Printf("%T %T\n", b, ‘2’))

Am self taught, just wondering if am right or is there any other better explanation of []byte{} and []byte().

1 Like

[]byte() is a typecast, just like int() for example is. You can cast strings to byte slices: []byte(“Hello World”)
[]byte{} initialises a slice, that can be filled with one byte runes, like []byte{‘H’, ‘e’, ‘l’, ‘l’, ‘o’}, or with bytes, like []byte{0, 1, 2, 3, 4}

5 Likes

Am sorry i just realize i didn’t thank you for the great explanation… Thank you

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.