0

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.

2
  • Go type declarations are on the form <var>[, <var>]* <type> so you are (in the last example) declaring a variable called int, with the type a and a variable b, without type. Commented Sep 23, 2014 at 13:01
  • 1
    See stackoverflow.com/questions/21071507/… Commented Sep 23, 2014 at 13:02

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

However, making order as 'var type' for argument 'a' results in the same error. But Thanks for 'IdentifierList'. It help me to got to understand its behavior.
I also want to add that In Go, whenever type of named function arguments are same then we can ignore type of all but last (tour.golang.org/#8)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.