lewisdale.dev/src/blog/posts/2024/5/learning-go-day-3.md
Lewis Dale 5aa6f37604
All checks were successful
Build and copy to prod / build-and-copy (push) Successful in 2m6s
Fix heading 3
2024-05-01 07:30:50 +01:00

2.6 KiB

title date tags excerpt
Learning Go: Day Three 2024-05-03T08:00:00.0Z
learning
go
For my third day of learning Go, I'm going to take a look at some control structures

Over the last two days I've learned how to setup and create a Go project, and then how to organise code into packages. I realise I've skipped a crucial step there, though, which is learning how to deal with control structures.

By control structures, I'm referring to things like for- loops, if statements, etc. You know, the things that make the software do things beyond just multiplying 2 by 5.

For-loops

The old trusty workhorse of any programming language. These seem pretty straightforward in Go, similar to most other languages:

// maths.go

// Calculate val to the n'th power
func Pow(val, n int) int {
    for i:= 1; i < n; i++ {
        val *= val
    }

    return val
}

// main.go

func main() {
	four_squared := maths.Pow(4, 2)
	fmt.Printf("4^2 = %d\n", four_squared)
}

Cool, this worked. I have successfully reinvented a small wheel1.

Do-While

The other trusty workhorse! Most languages have some form of this construct that says something like:

while statement is true:
    do something

But not Go, apparently! Or at least, not explicitly. In for-loops, the first and last arguments - defining a variable and performing an operation on it - are totally optional, so a while loop is just a for-loop2:

// maths.go

func Mod(a, b int) int {
    remainder := a
    for remainder >= b {
        remainder -= b
    }
    return remainder
}

If-else-then

The third trusty workhorseman of the Gopocalypse3. Basic if-statements are pretty straightforward:

// maths.go

func Divide(a, b int) int {
    if a == 0 {
        return 0
    }
    
    if b == 0 {
        return 0
    }

    return a / b
}

Which could be cleaned up to use else-if:

// maths.go

func Divide(a, b int) int {
    if a == 0 {
		return 0
	} else if b == 0 {
		return 0
	}
}

You can also add variable declarations to if-statements, which are then only accessible inside the blocks:

// maths.go

func Min(a, b int) int {
    if v := a - b; v > 0 {
        return b
    } else {
        return a
    }
}

Okay, so that's covered most of the control structures off the top of my head. On my to-do list for the next couple of days are: working with arrays, and testing.


  1. This particular wheel is a lot slower than the original wheel, but hey, I'm learning ↩︎

  2. Yes, yes, I know that's actually the case in many languages and while is just syntactic sugar ↩︎

  3. I'm sorry. ↩︎