function - Go函数声明语法

标签 function syntax go

刚开始学习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 inta, b int

关于function - Go函数声明语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25995539/

相关文章:

arrays - 如何在使用速记形式定义的数组中使用完全指定的类型?

golang : copy of context when copy is background

r - 使用 match.arg() 匹配默认值向量,有或没有错误 [R]

javascript - Node 需要目录而不是特定文件

JavaScript - getElementsByClassName 适用于一个函数,但不适用于另一个函数

python - 为什么 try-finally 有效,但 try-else-finally 无效?

go - 为什么这个 channel 操作会出现死锁错误?

go - 语法错误函数返回值

c# - 如何判断方法是否访问默认值

R哪个函数运行另一个函数