Go函数声明语法 [英] Go function declaration syntax

查看:103
本文介绍了Go函数声明语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆