Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parenthesis after a slice in go?

Tags:

slice

go

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?

like image 355
m0meni Avatar asked Oct 20 '22 09:10

m0meni


1 Answers

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.

like image 56
evanmcdonnal Avatar answered Oct 22 '22 02:10

evanmcdonnal