Tutorial by Examples

A simple function that does not accept any parameters and does not return any values: func SayHello() { fmt.Println("Hello!") }
A function can optionally declare a set of parameters: func SayHelloToMe(firstName, lastName string, age int) { fmt.Printf("Hello, %s %s!\n", firstName, lastName) fmt.Printf("You are %d", age) } Notice that the type for firstName is omitted because it is identical ...
A function can return one or more values to the caller: func AddAndMultiply(a, b int) (int, int) { return a+b, a*b } The second return value can also be the error var : import errors func Divide(dividend, divisor int) (int, error) { if divisor == 0 { return 0, errors.New(...
Return values can be assigned to a local variable. An empty return statement can then be used to return their current values. This is known as "naked" return. Naked return statements should be used only in short functions as they harm readability in longer functions: func Inverse(v float3...
A simple literal function, printing Hello! to stdout: package main import "fmt" func main() { func(){ fmt.Println("Hello!") }() } play it on playground A literal function, printing the str argument to stdout: package main import "fmt&quot...
A variadic function can be called with any number of trailing arguments. Those elements are stored in a slice. package main import "fmt" func variadic(strs ...string) { // strs is a slice of string for i, str := range strs { fmt.Printf("%d: %s\n", i, ...

Page 1 of 1