Function

What is it

func HelloWorld() string { return "Hello World" }
  • Function name of HelloWorld
  • returns string type
func add(x int, y int) int { return x + y }
  • Defines a function of name add
  • Defines Params
    • accept parameter of x which is of type int
    • accept parameter of y which is also of type int
  • Defines Return type
    • function returns type of int

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 parameters are 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 defer section.

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) }