Golang: Function

By Xah Lee. Date: . Last updated: .

Define Function

A function is defined like this:

func fname(param1 type1, param2 type2 …) return_type {body}

Note: type specification comes after the variable name.

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:

func f(x, y, z int) is same as func f(x int, y int, z int)

func f(x, y string, z int) is same as func f(x string, y string, z int)

package main

import "fmt"

func ff(x, y int) int {
	return x + y
}

func main() {
	fmt.Println(ff(3, 4))
}

Multiple Return Values

A function can return more than 1 value.

func ff() (int, int, int) { return 3, 4, 5 }

To get these values, assign them to multiple variables, like this:

var a, b, c = ff()

package main

import "fmt"

// returns 2 values
func ff(x, y int) (int, int) {
	return x, y
}

func main() {
	var a, b = ff(3, 4)
	fmt.Println(a, b)
}

// prints 3 4

Function with multiple return values is frequently used in golang. The second value is usually a error state.

Named Return Values

The return values can be named.

func fname(params) (return_var_name_1 return_var_1_type …) {body}

If named, they are treated as variables declared at the top of the function body.

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.

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
}

Nested Function

To define a function inside a function, declare a variable and give it a function value. Like this:

var f = func(…) … {…}

or use the variable shortcut:

f := func(…) … {…}

package main

import "fmt"

func main() {
	// this is a function, inside the function main
	var ff = func(x int) int {
		return x + 1
	}
	fmt.Println(ff(3)) // 4
}

Function as Argument

Function can be passed to another function as argument.

If a function is to take another function as argument, the tricky part is to specify the argument type, like this

func fname(fname f_type_spec) return_type {body}

where the f_type_spec is this form:

func (…) return_type2

example:

func f1(gg func(int) int) int { return gg(1) }

package main

import "fmt"

func aa(n int) int {
	return n + 1
}

// ff takes a function arg
func ff(gg func(int) int) int {
	return gg(1)
}

func main() {

	fmt.Println(ff(aa)) // 2

}

Return a Function

To have a function return a function, the tricky part is in the return type spec.

func f(…) return_type {body}

The return_type must be a function type, like this:

func (…) return_type2

The whole thing looks like this:

func f(…) func (…) return_type2 {body}

package main

import "fmt"

// ff returns a function gg
func ff(x int) func(int) int {
	var gg = func(y int) int { return y + x }
	return gg
}

func main() {
	fmt.Println(ff(1)(2)) // 3

}

Unspecified Number of Arguments

For unspecified number of argument (aka variadic function) , use this syntax, e.g.

func f(x ...type)

example:

func f(args …int)

The arguments are received as a slice type in the function body.

package main

import "fmt"

// function with unspecified number of args
func ff(x ...int) []int {
	return x
}

func main() {
	fmt.Printf("%#v\n", ff(3, 7))
	// []int{3, 7}
}

Pass Array Elements to Function

If you have a array (or slice) and you want to pass its elements to function as arguments, you can do:

ff(array ...)

[see Golang: Array]

[see Golang: Slice]

package main

import "fmt"

// add all args
func ff(args ...int) int {
	var total = 0
	for _, v := range args {
		total += v
	}
	return total
}

func main() {
	// slice
	var x = []int{3, 7, 10}

	// slice to args
	fmt.Printf("%v\n", ff(x...)) // 20
}

Closure

Golang: Closure

Reference

The Go Programming Language Specification - The Go Programming Language#Function_types

If you have a question, put $5 at patreon and message me.

Golang

  1. Compile, Run
  2. Source Encoding
  3. Package, Import
  4. Comment
  5. Print
  6. String
  7. Print String
  8. String Backslash Escape
  9. Rune
  10. Variable
  11. Zero Value
  12. Constant
  13. If Then Else
  14. Switch/Case
  15. Loop
  16. Basic Types
  17. Array
  18. Slice
  19. Map
  20. Struct
  21. Function
  22. Closure
  23. Pointer
  24. String, Byte Slice, Rune Slice
  25. regexp
  26. Read File
  27. Write to File
  28. Walk Dir
  29. Check File Exist
  30. System Call
  31. Get Script Path
  32. Defer
  33. Random Number

Examples

  1. Match Any Regexp
  2. Find Replace
  3. Validate Links
  4. Generate Sitemap

Reference

  1. Go Spec