为什么Golang将类型说明符放在变量名之后?

huangapple go评论63阅读模式
英文:

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为索引、映射到intmap类型。
    type Frequency map[string]int
  • 类型Point是一个具有两个字段xy,类型为intstruct类型。
    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 a map indexed by string, mapping to int<br>
    type Frequency map[string]int
  • The type Point is a struct with two fields, x and y of type int<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.

huangapple
  • 本文由 发表于 2016年11月20日 16:27:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/40702062.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定