We can use func
keyword to define a function.
Version
Golang 1.17.7
Function
main.go
package main
import "fmt"
func main() {
result := add(1, 2)
fmt.Println(result)
}
func add(x, y int) int {
return x + y
}
Line 1
package main
Declare main
package for the executable program.
Line 3
import "fmt"
Import fmt
package for using fmt.Println()
.
Line 5
func main() {
result := add(1, 2)
fmt.Println(result)
}
main()
is a special function and it’s the entry point of the executable program.
- Go is not an OOP-only language. We can define function directly
func
: define a function withfunc
keyword:=
: define a variable without type. The type is inferred automatically by Type Inferencefmt.Println
: print out the result
Line 10
func add(x, y int) int {
return x + y
}
add()
is a user-defined function.
x, y int
: parameterx
andy
are all typeint
. We can ignore to declare typeint
on the first parameterfunc add() int
: declare return typeint
of the function
We don’t have to define
add()
before usingmain()
Conclusion
func
keyword is so concise to define a function- We don’t have to use
:
to declare parameter type and function return type - We can use
:=
to define a local variable in the function instead ofvar