Function
What is it
func HelloWorld() string { return "Hello World" }
- Function name of
HelloWorld - returns
stringtype
func add(x int, y int) int { return x + y }
- Defines a function of name
add - Defines Params
- accept parameter of
xwhich is of typeint - accept parameter of
ywhich is also of typeint
- accept parameter of
- Defines Return type
- function returns type of
int
- function returns type of
Result parameter and Return
The result parameter acts as an ordinary local variable and the function may assign values to them after instantiation using return.
- Regardless of how
result parametersare declared, all the result values are initialized to the zero values for their type upon entry to the function.
A return statement that specifies results sets the result parameters before any deferred functions are executed.
- see
defersection.
When you have multiple return values in a function, result parameter must be wrapped in a parenthesis ().
func twoReturns() (r1 string, r2 string) { // ... }
Void return
In Go, returning nothing is implicit when no result parameter is defined.
// Valid function with no return value func sayHello(name string) { fmt.Println("Hello,", name) }
Error Handling Convention
When a function returns a err as second return value, you can use it to catch error.
// package.method() has two return values result, err := package.method() if err != nil { log.Printf("error calling package.method: %v", err) }