<< 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.
SliceGolang 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-InsHere: 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.orgGolang 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.
Related Links:
- Golang strconv, Convert Int to String
- Golang Odd and Even Numbers
- Golang Recover Built In: Handle Errors, Panics
- Learn Go Language Tutorial
- Golang html template Example
- Golang http.Get Examples: Download Web Pages
- Golang container list Example (Linked List)
- Golang base64 Encoding Example: EncodeToString
- Golang os exec Examples: Command Start and Run
- Golang String Between, Before and After
- Golang os.Remove: Delete All Files in Directory
- Golang First Words in String
- Golang flag Examples
- Golang Regexp Find Examples: FindAllString
- Golang Regexp Examples: MatchString, MustCompile
- Golang Index, LastIndex: strings Funcs
- Golang Compress GZIP Examples
- Golang Interface Example
- Golang 2D Slices and Arrays
- Golang Sscan, Sscanf Examples (fmt)
- Top 41 Go Programming (Golang) Interview Questions (2021)
- Golang Padding String Example (Right or Left Align)
- Golang Equal String, EqualFold (If Strings Are the Same)
- Golang map Examples
- Golang Map With String Slice Values
- Golang Array Examples
- Golang Remove Duplicates From Slice
- Golang If, Else Statements
- Golang ParseInt Examples: Convert String to Int
- Golang Strings
- Golang strings.Map func
- Golang bufio.ScanBytes, NewScanner (Read Bytes in File)
- Golang Built In Functions
- Golang bytes.Buffer Examples (WriteString, Fprintf)
- Golang Bytes: Slices and Methods
- Golang Caesar Cipher Method
- Golang Chan: Channels, Make Examples
- Golang Math Module: math.Abs, Pow
- Golang Reverse String
- Golang Struct Examples: Types and Pointers
- Golang path and filepath Examples (Base, Dir)
- Golang Substring Examples (Rune Slices)
- Golang Suffixarray Examples: New, Lookup Benchmark
- Golang switch Examples
- Golang Convert Map to Slice
- Golang Convert Slice to String: int, string Slices
- Golang Const, Var Examples: Iota
- Golang ROT13 Method
- Golang strings.Contains and ContainsAny
- Golang rand, crypto: Random Number Generators
- Golang String Literal Examples (Repeat Method)
- Golang ToLower, ToUpper String Examples
- Golang Trim, TrimSpace and TrimFunc Examples
- Golang Join Examples (strings.Join)
- Golang Len (String Length)
- Golang Convert String to Rune Slice (append)
- Golang JSON Example: Marshal, Unmarshal
- Golang Replace String Examples: Replacer, NewReplacer
- Golang nil (Cannot Use nil as Type)
- Golang Slice Examples
- Golang ListenAndServe Examples (HandleFunc)
- Golang Fibonacci Sequence Example
- Golang Time: Now, Parse and Duration
- Golang bits, OnesCount (Get Bitcount From Int)
- Golang Fprint, Fprintf and Fprintln Examples (fmt)
- Golang Func Examples
- Golang csv Examples
- Golang Fields and FieldsFunc
- Golang unicode.IsSpace (If Char Is Whitespace)
- Golang fmt.Println Examples
- Golang for Loop Examples: Foreach and While
- Golang ioutil.WriteFile, os.Create (Write File to Disk)
- Golang File Handling
- Golang range: Slice, String and Map
- Golang Readdir Example (Get All Files in Directory)
- Golang Sort Slice: Len, Less, Swap in Interface
- Golang Get Lines in File (String Slice)
- Golang Split Examples (SplitAfter, SplitN)
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