Parenthesis after a slice in go?

1.5k views Asked by At

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

There are 1 answers

2
evanmcdonnal On BEST ANSWER

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.