Golang Basics - Part 2: Control Structures and Functions
Introduction
In the previous part, we covered the basic syntax of Golang, including variables, data types, and basic input/output operations. In this part, we'll delve into control structures and functions, which are essential for writing more complex and organized code.
Control Structures
If-Else Statements
The if
statement in Golang allows you to execute a block of code based on a condition. The syntax is similar to other programming languages.
package main
import "fmt"
func main() {
age := 18
if age < 18 {
fmt.Println("You are a minor.")
} else if age == 18 {
fmt.Println("You just became an adult.")
} else {
fmt.Println("You are an adult.")
}
}
Switch Statements
The switch
statement provides an alternative to multiple if-else
statements. It's useful for comparing a variable against multiple values.
package main
import "fmt"
func main() {
day := "Tuesday"
switch day {
case "Monday":
fmt.Println("It's Monday.")
case "Tuesday":
fmt.Println("It's Tuesday.")
case "Wednesday":
fmt.Println("It's Wednesday.")
default:
fmt.Println("It's another day.")
}
}
For Loops
Golang uses the for
loop for iteration. It has a simple syntax and can be used in different forms.
package main
import "fmt"
func main() {
// Traditional for loop
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// While-like loop
j := 0
for j < 5 {
fmt.Println(j)
j++
}
// Infinite loop
k := 0
for {
fmt.Println(k)
k++
if k >= 5 {
break
}
}
}
Functions
Functions in Golang are first-class citizens, meaning they can be assigned to variables, passed as arguments, and returned from other functions.
Defining Functions
Here's how you define a simple function in Golang:
package main
import "fmt"
func add(a int, b int) int {
return a + b
}
func main() {
sum := add(3, 4)
fmt.Println("Sum:", sum)
}
Multiple Return Values
Golang functions can return multiple values, which is particularly useful for error handling.
package main
import "fmt"
func divide(a float64, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("cannot divide by zero")
}
return a / b, nil
}
func main() {
result, err := divide(10, 2)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
}
Named Return Values
Golang allows you to name the return values in a function signature, making your code more readable.
package main
import "fmt"
func swap(a, b int) (x int, y int) {
x = b
y = a
return
}
func main() {
a, b := swap(1, 2)
fmt.Println("Swapped:", a, b)
}
Conclusion
In this part of the Golang series, we've explored control structures and functions. These are fundamental concepts that will help you build more complex and structured programs. In the next part, we'll dive into more advanced topics like pointers, structs, and methods. Stay tuned!
Feel free to ask if you need any specific details or additional topics covered!