define function in go code example

Example 1: go functions

// a simple function
func functionName() {}

// function with parameters (again, types go after identifiers)
func functionName(param1 string, param2 int) {}

// multiple parameters of the same type
func functionName(param1, param2 int) {}

// return type declaration
func functionName() int {
    return 42
}

// Can return multiple values at once
func returnMulti() (int, string) {
    return 42, "foobar"
}
var x, str = returnMulti()

// Return multiple named results simply by return
func returnMulti2() (n int, s string) {
    n = 42
    s = "foobar"
    // n and s will be returned
    return
}
var x, str = returnMulti2()

Example 2: golang function

package main

import "fmt"

func basicFunction() {
	fmt.Println("basic function golang")
}

var variableFunction = func() {
	fmt.Println("basic function golang with variable function")
}

func parameterFunc(a, b int) {
	addition := a + b
	fmt.Println("total", addition)
}

func returningFunc(a, b int) int {
	addition := a + b
	return addition
}

func multipleReturningFunc(a, b int) (string, int) {
	multiple := a + b
	return "nilainya adalah", multiple
}

func multipleReturningNamingFunc(a, b int) (multiple, subtract int) {
	multiple = a * b
	subtract = a - b
	return
}

func variadicFunction(array ...int) (sum int) {

	for _, v := range array {
		sum = v
		fmt.Println(sum)
	}

	return
}

func anonymousFunc() {
	name := "john doe"
	func() {
		fmt.Println(name)
	}()
}

func anonymousParamsFunc() {
	name := "jane doe"
	func(str string) {
		fmt.Println(str)
	}(name)
}

func closureFunc() func() string {
	name := "john"
	return func() string {
		name += "doe"
		return name
	}
}

func main() {
	clousure := closureFunc()

	basicFunction()
	variableFunction()
	parameterFunc(10, 2)
	fmt.Println("total", returningFunc(10, 10))
	fmt.Println(multipleReturningFunc(40, 2))
	fmt.Println(multipleReturningNamingFunc(10, 2))
	variadicFunction(1, 2, 3, 4, 5)
	anonymousFunc()
	anonymousParamsFunc()
	fmt.Println(clousure())
	fmt.Println(clousure())
	fmt.Println(clousure())
}

Tags:

Go Example