英文:
Go function declaration syntax
问题
我刚开始学习Go语言,仍在努力理解一些东西。
我写了一个名为add
的函数:
func add(a int, b int) int {
return a + b
}
// 运行正常
func add(a, b) int {
return a + b
}
// ./hello.go:7: undefined: a
// ./hello.go:7: undefined: b
// 理解:也许我需要给出类型
func add(a, b int) int {
return a + b
}
// 运行正常,有趣的是
func add(a int, b) int {
return a + b
}
// ./hello.go:7: final function parameter must have type
我真的很困惑,或者由于缺乏知识而无法理解“最后的函数参数必须具有类型”的用例。
英文:
I have just started to learn Go
language and still trying to digest few things.
I wrote a function add
as:
func add(a int, b int) int {
return a + b
}
// works fine
func add(a, b) int {
return a + b
}
// ./hello.go:7: undefined: a
// ./hello.go:7: undefined: b
// Digested: May be I need to give type
func add(a, b int) int {
return a + b
}
// works fine interestingly
func add(a int, b) int {
return a + b
}
// ./hello.go:7: final function parameter must have type
I am really confused or due to lack of knowledge unable to understand the use case of
final function parameter must have type
.
答案1
得分: 1
我在“Can you declare multiple variables at once in Go?”中提到了IdentifierList
:它解释了a, b int
的含义。
但是在最后的int a, b
参数列表中,每个参数都需要有一个关联的类型,而这并不是这种情况。
按照变量声明规范,顺序始终是var type
,而不是type var
:
VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
在IdentifierList
之后总是会找到一个类型,例如a int
或a, b int
。
英文:
I mentioned the IdentifierList
in "Can you declare multiple variables at once in Go?": that explains a, b int
.
But you need to have a type associated to each parameters of a function, which is not the case in the last int a, b
parameter list.
The order is always var type
, not type var
, following the variable declaration spec:
VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
You would always find a type after an IdentifierList
: a int
or a, b int
答案2
得分: 1
以上都不完全正确。答案是Go语言允许你为每个参数显式地指定类型,例如a int, b int,或者使用更简短的表示法,其中你可以列出两个或多个用逗号分隔的变量,以及它们的类型。所以在a,b int的情况下,a和b都被定义为整数类型。你可以指定a,b,c,d,e,f int,在这种情况下,所有这些变量都被赋予int类型。这里没有"未定义"的类型。上面显示的声明形式(a,b)的问题是产生了错误,因为你没有为变量指定任何类型。
英文:
None of the above are quite correct. The answer is that Go allows you to explicitly give the type for each parameter, as a int, b int, or to use a shorter notation where you list two or more variables separated by commas, ending with the type. So in the case of a,b int - both a and b are defined to be of type integer. You could specify a,b,c,d,e,f int and in this case all of these variables would be assigned a type of int. There is no "undefined" type here. The problem with the (a,b) form of the declaration shown above produces an error because you have specified no type at all for the variables.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论