GoLang Fundamentals

Discover GoLang fundamentals effortlessly. Master syntax, data types, and concurrency in this concise guide. Elevate your coding skills now!
E
Edtoks3:57 min read

1. Variables and Constants

In Go, variables are containers for storing data values. They must be declared before use, specifying the type of data they will hold. For example, var age int = 25 declares an integer variable named age and initializes it with the value 25. The := syntax is a shorthand for variable declaration and initialization. In the example, name := "John" declares and initializes a string variable named name. These variables are then used in a fmt.Println statement to print a message to the console.

package main

import "fmt"

func main() {
    // Variable declaration and initialization
    var age int = 25

    // Short variable declaration
    name := "John"

    // Printing variables
    fmt.Println(name, "is", age, "years old.")
}

Constants in Go are variables whose values cannot be changed once assigned. They are declared using the const keyword. Enumerated constants are defined using the iota keyword to generate sequential values. In the provided example, the days of the week are declared as constants with sequential values starting from 1 using iota.

package main

import "fmt"

const (
    Monday = iota + 1
    Tuesday
    Wednesday
    Thursday
    Friday
)

func main() {
    fmt.Println("Days of the week:")
    fmt.Println("Monday:", Monday)
    fmt.Println("Tuesday:", Tuesday)
    fmt.Println("Wednesday:", Wednesday)
    fmt.Println("Thursday:", Thursday)
    fmt.Println("Friday:", Friday)
}

2. Data Types and Type Inference

Go is statically typed, meaning that variable types must be explicitly declared. Basic data types in Go include integers (int), floating-point numbers (float64), strings (string), and booleans (bool). Type conversion allows you to convert values between different types. In the example, an integer variable is converted to a float, demonstrating type conversion.

package main

import "fmt"

func main() {
    // Data types and type conversion
    var num1 int = 42
    var num2 float64 = float64(num1)
    result := float64(num1) / 2.0

    fmt.Println("Original integer:", num1)
    fmt.Println("Converted to float:", num2)
    fmt.Println("Result of division:", result)
} 

3. Control Flow

Control flow statements in Go include if statements for conditional execution and for loops for iteration. The first example demonstrates a basic if statement that checks if a person is eligible to vote based on their age.

package main

import "fmt"

func main() {
    // If statements
    age := 18

    if age >= 18 {
        fmt.Println("You are eligible to vote.")
    } else {
        fmt.Println("Sorry, you cannot vote yet.")
    }
}

The second example showcases a for loop for counting from 1 to 5 and looping through a collection (slice) of names.

package main

import "fmt"

func main() {
    // For loops
    for i := 1; i <= 5; i++ {
        fmt.Println("Count:", i)
    }

    // Looping through a collection
    names := []string{"Alice", "Bob", "Charlie"}

    for index, name := range names {
        fmt.Println("Index:", index, "Name:", name)
    }
}

4. Functions and Error Handling

Functions are a fundamental building block in Go. They are declared using the func keyword, and parameters and return types are specified. The first example defines a simple function greet that takes a name as a parameter and prints a greeting. The second example demonstrates a function with multiple return values and the invocation of both single and multiple return functions.

package main

import "fmt"

// Simple function
func greet(name string) {
    fmt.Println("Hello,", name)
}

// Function with multiple return values
func calculate(x, y int) (int, int) {
    sum := x + y
    difference := x - y
    return sum, difference
}

func main() {
    // Invoking functions
    greet("John")

    // Using multiple return values
    result1, result2 := calculate(10, 5)
    fmt.Println("Sum:", result1, "Difference:", result2)
}

Error handling in Go is explicit. Functions that may return an error include it in their return type. The calling code then checks for errors using if err != nil. The third example shows a function divide that returns an error if division by zero is attempted.

package main

import (
    "fmt"
    "errors"
)

// Function returning an error
func divide(x, y float64) (float64, error) {
    if y == 0 {
        return 0, errors.New("cannot divide by zero")
    }
    result := x / y
    return result, nil
}

func main() {
    // Handling errors
    result, err := divide(10, 2)
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("Result of division:", result)
    }
}

This module covers foundational concepts in Go, including variables, constants, data types, control flow, functions, and error handling. The examples provide hands-on experience to help learners understand the practical application of these concepts in Go programming.

Let's keep in touch!

Subscribe to keep up with latest updates. We promise not to spam you.