在Go语言中,为什么使用[]int而不是int[]?

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

in go, why []int instead of int[]?

问题

这个语法在很久以前就开始了,我不明白它的吸引力。

对我来说,即使有初始化,

var arr int[2]{ 1, 2 } // 错误!

var arr [2]int{ 1, 2 } // 对我来说这看起来很笨拙

更易读。


在更多人对我进行指责之前,请查看注释,并且答案中的链接正是我正在寻找的信息。

英文:

this syntax was started quite some time ago, and I do not understand its appeal

to me, even with initialization,
<pre>
var arr int[2]{ 1, 2 } // wrong!
</pre>
is more readable than
<pre>
var arr [2]int{ 1, 2 } // to me this seems klutzy
</pre>

<hr/>

before more people get on my case, please see notes, and link in answer was exactly the info I was seeking.

答案1

得分: 3

第二种方式对我来说更易读。这是一个观点问题。由于你没有创建这种语言,所以你的观点没有被采纳。

可能还有其他因素,比如第二种方式更容易解析。

这里有一篇关于Go语法选择的博客文章。听起来主要是为了可读性。

此外,与C语言的不同可能也起了一定作用(在这里找到):

数组的大小是其类型的一部分。类型[10]int和[20]int是不同的。

英文:

The second way is more readable to me. It's an opinion thing. Since you didn't create the language, your opinion wasn't the one adopted.

There may have also been other factors, such as the second way being easier to parse.

Here's a blog post on the Go syntax choices. It sounds like it was mostly about readability.

Also, this difference from C might play a part (found here):

> The size of an array is part of its
> type. The types [10]int and [20]int
> are distinct.

huangapple
  • 本文由 发表于 2011年6月12日 01:39:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/6317503.html
匿名

发表评论

匿名网友

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

确定