go functions in golang code example
Example 1: go functions
func functionName() {}
func functionName(param1 string, param2 int) {}
func functionName(param1, param2 int) {}
func functionName() int {
return 42
}
func returnMulti() (int, string) {
return 42, "foobar"
}
var x, str = returnMulti()
func returnMulti2() (n int, s string) {
n = 42
s = "foobar"
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())
}
Example 3: 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