英文:
Why does the golang place the type specifier "after" the variable name?
问题
只是出于好奇,为什么golang
将类型说明符放在变量名之后,像下面这样。是必须这样吗?还是碰巧这样?
type person struct {
name string
age int
}
为什么不像这样呢?在我看来,这样更自然,并且可以省略type
关键字。
struct person {
string name
int age
}
英文:
Just out of curiosity, why does the golang
place the type specifier after the variable name like below. Have to? Or happen to?
type person struct {
name string
age int
}
Why not just like this? It's more natural IMHO, and it saves the type
keyword.
struct person {
string name
int age
}
答案1
得分: 12
我认为Go编程语言遵循以下原则:
- 声明以关键字开头,这样解析器可以使用单个标记预读来实现(就像Pascal语言一样)。
- 声明的其余部分遵循英语语法,省略了每个多余的词(也类似于Pascal语言,但关键字更少)。
示例:
- 类型
Frequency
是一个以string
为索引、映射到int
的map
类型。
type Frequency map[string]int
- 类型
Point
是一个具有两个字段x
和y
,类型为int
的struct
类型。
type Point struct { x, y int }
上述句子更注重名称而不是类型,这是有道理的,因为名称传达了更多的含义。
如果我必须向初学者程序员解释如何在Go中编写声明,我会让他们首先用简单的英语描述,然后删除每个可能看起来多余的词。
到目前为止,我没有发现任何与这些规则相矛盾的地方。
英文:
I think the Go programming language follows these principles:
- declarations start with a keyword, so that the parser can be implemented with a single token look-ahead (like in Pascal)
- the rest of the declaration follows the English grammar, with every redundant word left out (also like in Pascal, but with fewer keywords)
Examples:
- The type
Frequency
is amap
indexed bystring
, mapping toint
<br>
type Frequency map[string]int
- The type
Point
is astruct
with two fields,x
andy
of typeint
<br>
type Point struct { x, y int }
The above sentences focus more on the names than on the types, which makes sense since the names convey more meaning.
If I had to explain to novice programmers how to write declarations in Go, I would let them first describe it in plain English and then remove every word that might even seem redundant.
Up to now, I didn't find any contradictions to these rules.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论