Golang functions: Difference between revisions
From wikinotes
No edit summary |
No edit summary |
||
Line 1: | Line 1: | ||
= Function Signatures = | |||
<blockquote> | |||
Function with arguments, return value | |||
<syntaxhighlight lang="go"> | <syntaxhighlight lang="go"> | ||
// (param type) (return-type) | // (param type) (return-type) | ||
Line 19: | Line 22: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Function Signatures --> | |||
= Deferred evaluation = | |||
<blockquote> | |||
Defer waits until a function is just about to exit (even on failure).<br> | |||
This is similar to a try/finally block in other languages.<br> | |||
Docs describe it as useful for releasing a mutex, for example. | |||
<syntaxhighlight lang=""> | |||
func WriteFile(filepath string) (success int) { | |||
fd, err := os.Open(filepath) | |||
defer fd.Close() // run before function closes | |||
// ... other code ... | |||
} | |||
</syntaxhighlight> | |||
</blockquote><!-- Deferred evaluation --> |
Revision as of 20:59, 23 May 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) { // ... }
Deferred evaluation
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 ... }