Basic Syntax in Go
Tags: beginners, programming, go, tutorial
Published: 2023-01-12 13:53:19

Go is a popular programming language known for its simplicity, performance, and robustness. In this article, we will take a look at some of the basic syntax in Go and how they are used in the language.

1. Variables: Variables in Go are an essential part of any program, as they allow you to store and manipulate data. There are several ways to declare a variable in Go. The first way is to use the "var" keyword:

    ```go
    // using the "var" keyword
    var x int

    // declaring multiple variables
    var x, y, z int

    // declaring multiple variables with different values    
    var x, y, z int = 5, 7, 9 

    // declaring multiple variables with different types
    var x, y, z = 5, "Hello", 7.5

    // declaring multiple variables without using the "var" keyword
    x, y, z := 5, "Hello", 7.5

    // declaring a variable without the "var" keyword
    x := 5
    ```

    The ":=" operator is a shortcut for declaring and initializing a variable, e.g. var x int = 5. It cannot be used outside a function, as the variable would not have a type.

2. Constants: In addition to variables, Go also supports constants, which are used to store values that do not change throughout the lifetime of a program. Constants are declared using the "const" keyword, followed by the constant name and the constant value. Here's an example of how you can declare a constant named pi with the value 3.14:

    ```go
    const pi float64 = 3.14
    ```

3. Functions: Functions are a fundamental building block in Go and are used to organize and reuse code. They are declared using the "func" keyword, mostly followed by the function name, and a set of parentheses that contain the function's parameters.

    ```go
    // declaring a function
    func add(x int) int {
        return x
    }

    // declaring a function with multiple parameters
    func add(x, y int) int {
        return x + y
    }

    // declaring a function with multiple return values
    func swap(x, y string) (string, string) {
        return y, x
    }

    // declaring a function with named return values
    func split(sum int) (x, y int) {
        x = sum * 4 / 9
        y = sum - x
        return
    }

    // declaring a function with a variable number of parameters
    func add(args ...int) int {
        total := 0
        for _, v := range args {
            total += v
        }
        return total
    }

    // declaring a function that returns a function
    func makeGreeter() func() string {
        return func() string {
            return "Hello, World!"
        }
    }
    ```
    Notes:
    - On the second last function, the `"args ...int"` is a special syntax called a "variadic function" which allows the function to take a variable number of arguments. It is represented by three dots (...) before the type which indicates that any number of arguments of type int can be passed to the function.
    - On the last function, the function is a higher-order function which returns another function. Inside makeGreeter, we are returning an anonymous function. This anonymous function is a function literal that has no name and takes no parameters, which is defined using the "func" keyword followed by a set of parentheses that contain no parameters and returns a string.

4. Control flow: Go provides a variety of control flow statements that allow you to control the flow of your program. These include if-else, for, and switch statements.

    ```go
    // if-else statement
    if x < 0 {
        return -x
    } else {
        return x
    }

    // for loop
    for i := 0; i < 10; i++ {
        fmt.Println(i)
    }

    // for loop with a condition
    for i < 10 {
        fmt.Println(i)
        i++
    }

    // switch statement
    switch os := runtime.GOOS; os {
    case "darwin":
        fmt.Println("OS X.")
    case "linux":
        fmt.Println("Linux.")
    default:
        fmt.Printf("%s.", os)
    }
    ```

5. Arrays: Arrays in Go are a fixed-size collection of elements of the same type. They are declared using the "[]" operator, followed by the size of the array and the element type.

    ```go
    // declaring an empty array with a length of 5
    var a [5]int 
    b := [5]int

    // declaring an array with a length of 5 and initializing it with values
    var a [5]int = [5]int{1, 2, 3, 4, 5}
    b := [5]int{1, 2, 3, 4, 5}
    ```

6. Slices: Slices are a more flexible alternative to arrays in Go and can be created using the "make" function. They are declared with the "[]" operator without a size.

    ```go
    // declaring a slice with a length of 5
    a := make([]int, 5)

    // declaring a slice with a length of 5 and a capacity of 10
    b := make([]int, 5, 10)

    // declaring a slice with a length of 5 and initializing it with values
    c := []int{1, 2, 3, 4, 5}

    // declaring a slice with a length of 5 and a capacity of 10 and initializing it with values
    d := make([]int, 5, 10)
    d = []int{1, 2, 3, 4, 5}    
    ```

7. Maps: Maps are a collection of key-value pairs in Go. They are declared using the "map" keyword, followed by the key type and the value type.

    ```go
    // declaring a map with a key type of string and a value type of int
    a := make(map[string]int)

    // declaring a map with a key type of string and a value type of int and initializing it with values
    b := map[string]int{
        "one": 1,
        "two": 2,
        "three": 3,
    }
    ```

8. Structs: Structs are a collection of fields in Go. They are declared using the "struct" keyword, followed by the name of the struct and a set of curly braces that contain the fields.

    ```go
    // declaring a struct
    type Person struct {
        Name string
        Age int
    }

    // declaring a struct with a field that is a pointer to another struct
    type Person struct {
        Name string
        Age int
        Address *Address
    }

    // declaring a struct with a field that is a slice
    type Person struct {
        Name string
        Age int
        Languages []string
    }

    // declaring a struct with a field that is a map
    type Person struct {
        Name string
        Age int
        Languages map[string]string
    }
    ```

9. Interfaces: Interfaces are a set of method signatures in Go. They are declared using the "interface" keyword, followed by the name of the interface and a set of curly braces that contain the method signatures.

    ```go
    // declaring an interface
    type Greeter interface {
        Greet()
    }

    // declaring a struct that implements the Greeter interface
    type Person struct {
        Name string
    }

    func (p *Person) Greet() {
        fmt.Println("Hello, my name is", p.Name)
    }
    ```

10. Pointers: Pointers are a reference to a value in Go. They are declared using the "\*" operator, followed by the type of the value that the pointer points to.

    ```go
    // declaring a pointer to an int
    var a *int

    // declaring a pointer to a struct
    var b *Person
    ```