Reputation: 8840
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
.
Upvotes: 0
Views: 1715
Reputation: 11
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.
Upvotes: 1
Reputation: 1323953
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
Upvotes: 1