TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to GO

Golang Func Examples

Create methods with the func keyword. See arguments and multiple return values.
Func. Think of a planet. It has a position in the solar system. As time passes the planet moves. Its position is a function of time.
In Go (with func) we specify functions. With multiple return values, methods can be more clearly written. Return values have names and positions.
An example. Let us start with a simple example—we create a func named "display" that receives 2 arguments of type int. It returns nothing.

Void: This is a void method. But there is no keyword void we use—Go just omits the return type.

Types: Both arguments (apples, oranges) to this method are of type int. The int is specified after the argument name.

Golang program that uses func with two arguments package main import "fmt" func display(apples int, oranges int) { // Display count of apples and oranges. fmt.Println(apples) fmt.Println(oranges) } func main() { // Call display method. display(10, 12) } Output 10 12
Multiple return values. Sometimes a method has no return value. But often we have one or more things to return—new objects, numbers, results.

Syntax: We specify this method, firstAndLast, has two return values. These are (int, int): specified after the argument.

Return: We can return two arguments by using a return-statement with a comma in it.

Here: In main we pass a slice to firstAndLast, and it returns the first and last elements in the slice.

Slice
Golang program that uses multiple return values package main import "fmt" func firstAndLast(items []int) (int, int) { // Return two values. return items[0], items[len(items) - 1] } func main() { data := []int{5, 50, 500, 5000} // Assign values to result of method. first, last := firstAndLast(data) // Display results. fmt.Println(first) fmt.Println(last) } Output 5 5000
Named return values. Optionally we can provide names to return values. In the method, we can use those named values like variables or arguments.

Default: The default value for an int return value is 0. So they do not need to be assigned before returning them again.

Program: Here we enhance firstAndLast so that it sets the "first" and "last" arguments only if the slice has at least two elements.

Golang program that uses named return values, defaults package main import "fmt" func firstAndLast(items []int) (first int, last int) { // If slice is at least two elements, set first and last. // ... Otherwise, leave the return values as zero. if len(items) >= 2 { first = items[0] last = items[len(items)-1] } return first, last } func main() { // For a zero-element slice, both return values are 0. data := []int{} fmt.Println(firstAndLast(data)) // The first and last values are set. data = []int{9, 8, 7, 6} fmt.Println(firstAndLast(data)) } Output 0 0 9 6
Func local, argument. A func can be the value in an assignment statement. Here we assign to the variable "f" a func that receives a rune and returns a bool.

Argument: We can pass the func variable as an argument to a method (like IndexFunc) that requires a func argument.

Result: The func returns true on the comma and space characters. So it returns 3 in both uses.

Golang program that uses func as local variable package main import ( "fmt" "strings" ) func main() { f := func(c rune) bool { // Return true if space or comma rune. return c == ' ' || c == ','; } value := "cat,bird" // Pass func object to IndexFunc method. result := strings.IndexFunc(value, f) fmt.Println(result) value = "cat bird" result = strings.IndexFunc(value, f) fmt.Println(result) } Output 3 3
Variable arguments. A variadic function accepts a variable number of arguments. We specify this with an ellipsis (three periods) in the argument list, as part of the final argument.

Usage: We use the variadic argument with the same syntax as a slice. We can use len(), range and access elements.

Golang program that uses func with variable argument list package main import "fmt" func PrintSum(name string, values ...int) { sum := 0 // Loop over all variadic arguments and sum them. for i := range(values) { sum += values[i] } fmt.Println(name, sum) } func main() { // Call variable-argument method. PrintSum("cat", 1, 2, 3) PrintSum("dog", 10, 20) PrintSum("ant") } Output cat 6 dog 30 ant 0
Defer. The defer keyword is used to specify a function (or expression) that is executed right before a func returns. If the defer func returns nil, a panic will occur.

Tip: We use defer to specify error-handing logic, as with the recover() method. But it can be used in other methods (like for cleanup) too.

RecoverBuilt-Ins

Here: The example() method sets its return value count to 10 in a defer func. This always changes the result to 10.

Quote: Instead, deferred functions are invoked immediately before the surrounding function returns.... If a deferred function value evaluates to nil, execution panics when the function is invoked.

Go Language Specification: golang.org
Golang program that uses defer package main import "fmt" func example() (count int) { defer func() { // Set result to 10 right before the return is executed. count = 10 }() return count } func main() { fmt.Println(example()) } Output 10
Funcs are powerful. Their multiple return values are useful for concurrency in programs. A complex computation, run on a thread, often has more than one thing to return.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf