刚开始学习Go
语言,仍在尝试消化一些东西。
我写了一个函数 add
作为:
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
我真的很困惑或由于缺乏知识而无法理解
的用例最终函数参数必须有类型
。
最佳答案
我提到了 IdentifierList
在“Can you declare multiple variables at once in Go?”中:解释了a, b int
。
但是你需要有一个类型关联到一个函数的每个参数,而在最后的int a, b
参数列表中不是这样。
顺序始终是 var type
,而不是 type var
,在 variable declaration spec 之后:
VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
您总是会在IdentifierList
之后找到一个类型:a int
或a, b int
关于function - Go函数声明语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25995539/