Golang: Function
Define Function
func fname(param1 type1, param2 type2, etc) returnType {body}
-
Defines a function.
package main import "fmt" func ff(x int, y int) int { return x + y } func main() { fmt.Println(ff(3, 4)) // 7 }
Omit Type Spec
Type spec can be omitted when they are the same as the last var's type.
Examples:
Following are equivalent:
func f(x, y, z int)
func f(x int, y int, z int)
Following are equivalent:
func f(x, y string, z int)
func f(x string, y string, z int)
Return Variable Syntax Shortcut
function return spec can contain variable names.
func fname(params) (name type) {body}
The name, is shothand for declaring the variable at the top of the function body.
For example, following are equivalent:
func f(x int) int { var r = x + 1; return r }
func f(x int) (r int) { r = x + 1; return r }
package main import "fmt" func gg(n int) (m int) { m = n + 1 return m } func main() { fmt.Println(gg(5)) } // 6
Function is a Value
Function is a value. It can be assigned to a variable, passed as argument to a function, or returned by a function.
Example:
var hh = func(x int) int { return x+1 }
package main import "fmt" // assign a function to a variable var hh = func() int { return 3 } func main() { fmt.Println(hh()) // 3 }
Apply Function to Value, Inline
Function can be applied by appending (arguments)
to the function definition or name.
Example:
func(x int) int { return x + 1 }(3)
package main import "fmt" func main() { var y = func(x int) int { return x + 1 }(3) fmt.Println(y) // 4 }