go functions why have * 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: go functions

package main

import "fmt"

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

func main() {
	fmt.Println(add(42, 13))
}
Notice that the type comes after the variable name

Tags:

Go Example