Golang functions: Difference between revisions

From wikinotes
Line 29: Line 29:
     // ...
     // ...
}
}
</syntaxhighlight>
Param values vs pointers
<syntaxhighlight lang="go">
// if 'name' param changes in func, does not change outside
func register immutable(name string) { ... }
// if 'name' param changes in func, modifies value in memory
func register_mutable(*name string) { ... }
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Function Signatures -->
</blockquote><!-- Function Signatures -->

Revision as of 02:05, 6 June 2022

Function Signatures

Function with arguments, return value

//        (param  type) (return-type)
func greet(name string) string {
    return "Hello, " + name
}

Multiple return values

// when multiple return values present, surround with brackets
func find(id int) (string, int) {
    // ...
}

// optionally, return values can be named
// (this has no implications for caller, it's simply documentation)
func find(id int) (name string, age int) {
    // ...
}

Combine params with same type

// params 'firstname', 'lastname' both have type 'string'
func register(firstname, lastname string) {
    // ...
}

Param values vs pointers

// if 'name' param changes in func, does not change outside
func register immutable(name string) { ... }

// if 'name' param changes in func, modifies value in memory
func register_mutable(*name string) { ... }

Deferred functions

Defer waits until a function is just about to exit (even on failure).
This is similar to a try/finally block in other languages.
Docs describe it as useful for releasing a mutex, for example.

func WriteFile(filepath string) (success int) {
    fd, err := os.Open(filepath)
    defer fd.Close()  // run before function closes

    // ... other code ...
}
  • Deferred functions are executed in the order of last-in-first-out (LIFO).
  • Panics evaluate after deferred functions

Variables passed to a defferred function retain their value at the time the function call was made.

func main() {
    a := "start"
    defer fmt.Println(a)
    b := "end"
}
// "start"   <-- 'a' at time of defer was 'start'

Anonymous Functions

You can define anynymous functions in go

foo = func() { ... }
defer func() { ... }