Functions are declared with func. They can have arguments and they may return values.
You can assign functions to variables.
Functions starting with a small caps character are only available within the module, Upper Caps are exported.
A simple declaration of a function is:
func functionName(parameter) return_type {
}
1 package main
2
3 import ( "fmt")
4
5 func main(){
6
7 c := add(1,2)
8 fmt.Println(c)
9 }
10
11 func add(a int, b int) int{
12 return a+b
13 }
package main
import ( "fmt")
func main(){
c := add(1,2)
fmt.Println(c)
}
func add(a int, b int) int{
return a+b
}
Line 5: we declare the main function. This is always called when a GO programm ist started.
Line 7: First the function add is called with the parameters “1” and “2”, which are int typed values. Note that the function add is declared after the function main and can be called. The result of the function add is assigned to c. The variable c is implicitly defined as int.
Line 11: If you only have one return value, you dont need “()” around the return value.
Line 12: You could assign “a+b” to another variable first, but as we do not use the value before this is not needed.
1 package main
2
3 import ( "fmt")
4
5 func main(){
6 var operations func(int,int) int
7 operations = func(a int, b int) int{
8 return a+b
9 }
10
11 c := operations(1,2)
12 fmt.Println(c)
13
14 operations = func(a int, b int) int{
15 return a-b
16 }
17
18 c = operations(1,2)
19 fmt.Println(c)
20
21
22 }
package main
import ( "fmt")
func main(){
var operations func(int,int) int
operations = func(a int, b int) int{
return a+b
}
c := operations(1,2)
fmt.Println(c)
operations = func(a int, b int) int{
return a-b
}
c = operations(1,2)
fmt.Println(c)
}
go run main.go
3
-1
Line 18: Although its the same code as in line 11, it gives a different result, because the first time in line 11 we call a+b and the second time in line 18 we call *a-b'.