Day 4 - Functions
Functions in Go
1) Creating a Function
func FunctionName() {
// block of code to execute
}
You can call the function using:
FunctionName()
This will execute the block of code inside the function.
2) Creating a Function with Parameters
func Add(a int, b int) {
fmt.Println(a + b)
}
Add(5, 6)
This will print the sum of the two numbers, 5 & 6 = 11.
Here, we provided two parameters to the function, a and b, of type int. You can also pass multiple parameters with their respective types.
3) Function with Return Values
func Add(a int, b int) int {
return a + b
}
sum := Add(5, 6)
fmt.Println(sum)
The Add function returns the sum of a and b, which is then stored in the variable sum.
We specify the return type after the parameter list.
Returning Multiple Values
Function with Named Return Values
func Calculator(a, b int) (sum int, sub int, mul int, div float32) {
sum = a + b
sub = a - b
mul = a * b
div = float32(a) / float32(b)
return
}
Here, we have multiple return values, each with different types. Since we named the return values, we didn't need to declare them again inside the function.
Function with Unnamed Return Values
func Greeting(hour int, name string) (string, string) {
var greet string
if hour >= 5 && hour < 12 {
greet = "Good morning"
} else if hour >= 12 && hour < 17 {
greet = "Good afternoon"
} else if hour >= 17 && hour < 21 {
greet = "Good evening"
} else {
greet = "Good night"
}
str1 := fmt.Sprintf("%s, %s!", greet, name)
str2 := fmt.Sprintf("Hope you're having a great time, %s!", name)
return str1, str2
}
In this example, only the return types are given, without naming the return variables.
Complete Example
package main
import (
"fmt"
)
func Calculator(a, b int) (sum int, sub int, mul int, div float32) {
sum = a + b
sub = a - b
mul = a * b
div = float32(a) / float32(b)
return
}
func Greeting(hour int, name string) (string, string) {
var greet string
if hour >= 5 && hour < 12 {
greet = "Good morning"
} else if hour >= 12 && hour < 17 {
greet = "Good afternoon"
} else if hour >= 17 && hour < 21 {
greet = "Good evening"
} else {
greet = "Good night"
}
str1 := fmt.Sprintf("%s, %s!", greet, name)
str2 := fmt.Sprintf("Hope you're having a great time, %s!", name)
return str1, str2
}
func main() {
sum, sub, mul, div := Calculator(5, 6)
fmt.Println(sum, sub, mul, div)
str1, str2 := Greeting(9, "Kalki")
fmt.Println("These are the strings:", str1, str2)
}
Output
11 -1 30 0.8333333
Good morning, Kalki!
Hope you're having a great time, Kalki!
Summary
- Functions help organize reusable blocks of code.
- You can pass parameters to functions.
- Functions can return single or multiple values.
- Return values can be named or unnamed.
Mastering functions is essential to writing clean and efficient Go code!