Golang basics: function declaration
To document my learning in Golang, here are some basic syntax rules for Golang functions.
- A function can take zero or more arguments
- The types comes after the variable name
func add(x, y int) int {
return x, y
}
// func add(x int, y int) int is also fine
func main() {
fmt.Println(add(42, 13))
}
// 55
Expression
func main() {
add := func(x, y int) int {
return x + y
}
fmt.Println(add(5,6))
}
// 11
Multiple results
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("hello", "world")
fmt.Println(a, b)
}
// world hello
- To do swap, we can also directly use
a, b = b, a.
Named return values (Naked return)
- A
return
statement without arguments returns the named return values. - Encouraged be used only in short functions because it might harm readability in longer functions
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return
}
func main() {
fmt.Println(split(17))
}
// 7 10
//
Return a function
func foo() func() int {
return func() int {
return 100
}
}
// the returned function will return an int
func main() {
bar := foo() // bar will be a function
fmt.Printf("%T\n", bar) // print the type: func() int
fmt.Println(bar()) // 100
}
Reference
fmt package - fmt - Go Packages
A Tour of Go
[Golang] function & method 函式與方法 | PJCHENder 未整理筆記
函式宣告
