Functions in Go.
Francis Sunday
Posted on November 24, 2017
In this part of the series, we're going to look at Functions, and how they work in Go.
What is a Function?
A function is a block of code that performs a specific task. A function takes an input, performs some calculations on the input and generates an output.
There are two types of functions you'd make use of in Go. 1) User-defined and 2) Standard functions.
User-defined Functions
This type of function, we create ourselves to perform a specific task in a program.
Declaration
Here's the syntax to declare a function:
...
func sayHello() {
fmt.Println("Hello World!")
}
In the sample code above, we declared a function sayHello
which prints the string Hello World
when the function is called. Every function in Go, starts with the func
keyword followed by the function name (we'll talk about naming conventions in a later article), and parenthesis, and then a block wrapped in between curly braces ({ }
).
...
func greet(name string) {
fmt.Println("Hello " + name)
}
The example above is another function, this time it takes in a parameter. See parameters as pieces of information that further defines a Function. In the code above, we declared a function greet
which accepts a parameter name
of type string. Calling this function is straight and simple:
...
func main() {
greet("Francis Sunday")
}
func greet(name string) { ... }
PS: When using parameters, its required to explicitly define its type.
package main
import "fmt"
func split(number int) (int, int) {
x := number * 4 / 9
y := number - x
return
}
func main() {
x, y := split(100)
fmt.Println("%d + %d = 100", x, y)
}
In the code above, we declare a function split
which accepts a single integer as a parameter number
. The function takes a parameter of type int
, and returns two numbers of type int
that sums up to the input parameter.
Running the program you should get the following:
$ go run functions.go
44.44 + 55.56 = 100
In this article, we've looked at Functions in Go, how they help use organize repetitive tasks into smaller blocks of code we can reuse any where in our program. In a later article in this series, we'd explore more on Functions.
Feel free to leave a comment if I've missed something important.
Posted on November 24, 2017
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.