Go函数声明语法 [英] Go function declaration syntax
问题描述
我刚刚开始学习 Go
语言,并仍在尝试消化一些东西。
我写了一个函数 add
为:
func add(a int,b int)int {
返回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函数参数必须有类型
我真的很困惑或由于缺乏知识,无法理解
的最终函数参数的用例必须具有类型
。
我提到了 IdentifierList
在 Can你在Go中一次声明多个变量?:这解释了 a,b int
。
但是你需要一个与函数的每个参数关联的类型,这在上一个 int a,b
参数列表中不是这种情况。
订单总是 var type
,而不是 type var
,跟在变量声明规范:
VarSpec = IdentifierList(Type [=ExpressionList] | =表达式列表)。
在之后总是会找到一个类型 IdentifierList : a int
或 a,b int
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
.
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
这篇关于Go函数声明语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!