英文:
Parenthesis after a slice in go?
问题
最近我开始学习Go,并按照一个教程进行学习(链接:https://golang.org/doc/articles/wiki/)。在教程中有一行代码:
p1 := &Page{Title: "TestPage", Body: []byte("This is a sample Page.")}
他们使用括号定义了一个切片:
[]byte("This is a sample Page.")
然而,从我阅读的所有文档中,我从未见过在切片后面使用括号。我只见过以下格式:
b := []byte{'g', 'o', 'l', 'a', 'n', 'g'}
使用花括号。括号的作用是什么?
英文:
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
得分: 4
从规范中可以看出:
将字符串类型的值转换为字节切片类型会产生一个切片,其中连续的元素是字符串的字节。
[]byte("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
[]byte("") // []byte{}
MyBytes("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
在这两行代码中,虽然它们产生相同的行为,但实际上它们使用了完全不相关的语言特性。在[]byte{'l', 'o', 'l'}
的情况下,你只是使用了复合字面量语法进行初始化,这在任何类型中都可以正常工作。而在另一种情况下,发生了一次转换,而且这是字符串的一个特殊情况。它看起来更像是在调用一个构造函数(从而使其成为复合字面量语法的替代),但这只是巧合。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论