2018-10-30 22:02
浏览 640


a := []byte("H") //works
a := []byte{"H"} //does not compile

What is the conceptual difference between () and {} as used above?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doujue6196
    doujue6196 2018-10-30 22:29

    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
    点赞 评论
  • dongzhuifeng1843
    dongzhuifeng1843 2018-10-30 22:10

    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
    点赞 评论