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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With