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?
From the spec;
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.