dongya9346
dongya9346
2015-06-11 16:54

切成薄片后加括号?

  • slice
已采纳

I've recently started learning go, and following through a tutorial. In the tutorial there is the line:

p1 := &Page{Title: "TestPage", Body: []byte("This is a sample Page.")}

They have a slice with parenthesis defined:

[]byte("This is a sample Page.")

However from all the docs I've read I've never seen parenthesis after a slice. I've only seen the format:

b := []byte{'g', 'o', 'l', 'a', 'n', 'g'}

Using the curly braces. What is the role of the parenthesis?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • drc15469 drc15469 6年前

    From the spec;

    Converting a value of a string type to a slice of bytes type yields a slice whose successive elements are the bytes of the string.

    []byte("hellø")   // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
    []byte("")        // []byte{}
    
    MyBytes("hellø")  // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
    

    Check out the full conversion rules here; https://golang.org/ref/spec#Conversions

    Based upon that, while the two lines of code result in the same behavior they are actually exercising completely unrelated language features. In the []byte{'l', 'o', 'l'} case you're simply using composite literal syntax for initilization and this will always work with any types. In the other case a conversion is occurring, and beyond that it's a special case for strings. It happens to look much more like a constuctor is being called (thus making it a substitute for the composite literal syntax) but that is just coincidence.

    点赞 评论 复制链接分享

为你推荐