Reputation: 4027
a := []byte("H") //works
a := []byte{"H"} //does not compile
What is the conceptual difference between () and {} as used above?
Upvotes: 7
Views: 3563
Reputation: 156434
The reason is the difference between type conversions and slice literals.
_ = []byte("Hi!") // Converts a string literal to a []byte.
_ = []byte{'H', 'i', '!'} // Initializes a []byte literal
Your second example []byte{"H"}
fails to compile because "H"
is a string literal that is being used in place of a rune literal, it's comparable to trying to assign a string to a byte typed variable:
var y byte = 'H' // OK
var x byte = "H" // ERROR: cannot use "H" (type string) as type byte in assignment
Upvotes: 11
Reputation: 43810
In the first one a := []byte("H")
you are type casting the string "H"
into a byte array.
In the second one a := []byte{"H"}
you are defining a byte array and assigning "H" as it's first value, which is invalid.
You can compare the second one with defining a string array:
s := []string{"hello","world",".."} // works
f := []string{1,2,4} // fails because the datatype is wrong
Upvotes: 5