Kevin De Baerdemaeker

Golang

Modified 2025-01-22

Why was Go created?

Project Structure

Not a hard rule, but based on common conventions.

.
|-- go.mod
|-- readme.md
|-- tests
|-- cmd
|   |-- app
|       |-- main.go
|-- internal
|   `-- module1
|       `-- module1.go
`-- pkg

Useful Libraries

air

automatic recompile and run

Modules

Control Structures

Conditionals

There's a special if/else structure where you can declare a variable that's in-scope for only the if/else. Not really a thing in most languages.

if message := "hello"; user != nil {
	// message available
} else {
	// message available
}

Loops

There's only for, no do-while, no while

Interface

You only need to define the methods for each struct in order to implement the interface. So for example, if you have the following Rectangle.

type Rectangle struct {
    Width, Height float64
}

func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

func (r Rectangle) Perimeter() float64 {
    return 2 * (r.Width + r.Height)
}

If in the same package, an interface is defined like so.

type Shape interface {
    Area() float64
    Perimeter() float64
}

This, implicitly means that the Rectangle implements the Shape interface. Meaning, that you can pass in Rectangles to functions which expect a Shape.

func PrintShapeDetails(s Shape) {
    fmt.Printf("Area: %f, Perimeter: %f\n", s.Area(), s.Perimeter())
}

func main() {
    r := Rectangle{Width: 10, Height: 5}
    PrintShapeDetails(r)
}

Concurrency

For now, I understand goroutines as just creating a lightweight thread, which means that whatever function is called in the goroutine will running separately from the rest.

Read Tour of Go - Concurrency

Testing

When testing you can use the package packageName name itself, when you are testing internal functions. If you'd like to test from a package consumption perspective you opt for package packageName_test.

References

How to Start?

How to gain deeper knowledge?