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!

0
Subscribe to my newsletter

Read articles from Dhruvkumar Maisuria directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dhruvkumar Maisuria
Dhruvkumar Maisuria

About Me As a dedicated tech enthusiast with a passion for continuous learning, I possess a robust background in software development and network engineering. My journey in the tech world is marked by an insatiable curiosity and a drive to solve complex problems through innovative solutions. I have honed my skills across a diverse array of technologies, including Python, AWS, SQL, and Golang, and have a strong foundation in web development, API testing, and cloud computing. My hands-on experience ranges from creating sophisticated applications to optimizing network performance, underscored by a commitment to excellence and a meticulous attention to detail. In addition to my technical prowess, I am an avid advocate for knowledge sharing, regularly contributing to the tech community through blogs and open-source projects. My proactive approach to professional development is demonstrated by my ongoing exploration of advanced concepts in programming and networking, ensuring that I stay at the forefront of industry trends. My professional journey is a testament to my adaptability and eagerness to embrace new challenges, making me a valuable asset in any dynamic, forward-thinking team. Whether working on a collaborative project or independently, I bring a blend of analytical thinking, creative problem-solving, and a deep-seated passion for technology to every endeavor.