In a previous article, we covered the basics of the Go language
Go basics
. This time, we will delve deeper into Go’s functions.
-
Function declaration
-
Multiple return values
-
Functions as types
-
Recursivity
-
Methods
-
Functions with variable input
If you are new to the world of Go, I recommend the following previous articles:
Function declaration:
Inside the parentheses, the types of the input variables are indicated.
package main
import "fmt"
func main() {
repeat("AlfaExploit", 5)
}
func repeat(word string, reps int) {
for i := 0; i < reps; i++ {
fmt.Println(word)
}
}
If the function returns a value, the type of the returned value will be indicated outside the parentheses:
package main
import "fmt"
func addition(a, b int) int {
return a + b
}
func main() {
result := addition(3, 5)
fmt.Println(result)
}
Multiple return values:
It is similar to returning an array of values.
package main
import "fmt"
func divisionAndRemainder(dividend, divisor int) (int, int) {
quotient := dividend / divisor
remainder := dividend % divisor
return quotient, remainder
}
func main() {
quotient, remainder := divisionAndRemainder(10, 3)
fmt.Println(quotient, remainder)
}
Functions as types:
It’s about using a variable as a function, in this example, the variable operation
behaves as if it were the multiplication
function.
package main
import "fmt"
type Operation func(int, int) int
func multiplication(a, b int) int {
return a * b
}
func main() {
var operation Operation = multiplication
result := operation(2, 3)
fmt.Println(result)
}
Recursivity:
package main
import "fmt"
func factorial(n int) int {
if n <= 1 {
return 1
}
return n * factorial(n-1)
}
func main() {
result := factorial(5)
fmt.Println(result)
}
Methods:
It’s like having a structure that, in addition to having variables inside it, also has functions.
package main
import "fmt"
type Rectangle struct {
Base int
Height int
}
func (r Rectangle) Area() int {
return r.Base * r.Height
}
func main() {
rect := Rectangle{Base: 3, Height: 4} // Assign structure variable values
// rect structure moreover has Area function available
area := rect.Area() // Call structure function
fmt.Println(area)
}
Functions with variable input:
Variable number of input variables.
package main
import "fmt"
func addition(nums ...int) int {
result := 0
for _, num := range nums {
result += num
}
return result
}
func main() {
total := addition(1, 2, 3, 4)
fmt.Println(total)
total = addition(1, 2, 3, 4, 5)
fmt.Println(total)
}