GoLang Day 2: Messing With Modules

⌂ home      ⇧ one level up
Mon Jan 9, 2023 · 432 words · 3 min

Starting today from the Create a Go module tutorial.

The first peculiar thing I find is this

Go code is grouped into packages, and packages are grouped into modules. Your module specifies dependencies needed to run your code, including the Go version and the set of other modules it requires.

Modules being grouped under packages would've made more sense nomenclature wise, isn't it?

To create a module, you do

go mod init module-path

Important to note:

If you publish a module, this must be a path from which your module can be downloaded by Go tools. That would be your code's repository.

More info: Managing Dependencies

You get a go.mod file listing your code's dependencies. For obvious reasons, it starts with zero dependencies.

func Hello(name string) string {
    message := fmt.Sprintf("Hi, %v. Welcome!", name)
    return message
}

name string. Basically C++ style of declaring parameters, but order of datatype and identifier changed. And the return type comes at the end instead of the beginning.

About the function name starting with capital letter

In Go, a function whose name starts with a capital letter can be called by a function not in the same package. This is known in Go as an exported name. For more about exported names, see Exported names in the Go tour.

:= is a shorthand for declaring and assigning a variable. The same can be written as

var message string
message = fmt.Sprintf("Hi, %v. Welcome!", name)

Sprintf is creating a formatted string. Reeks of printf from C. I can guess %v to be a format specifier. Though I'll look up about that later. Also, Sprintf starts with capital S so that we can call it from outside of fmt module too?

Moving on to Call your code from another module

In module hello, added following code in hello.go

package main

import (
    "fmt"

    "example/greetings"
)

func main() {
    message := greetings.Hello("cakes")
    fmt.Println(message)
}

This won't be able to resolve "example/greetings" because that module isn't published. We must run the command below to ask Go to replace "example/greetings" with "../greetings".

go mod edit -replace example/greetings=../greetings

Note that the tutorial uses example.com/greetings as the module path, while I have used example/greetings.

Run go mod tidy.

The go.mod file should have these two lines appended.

replace example/greetings => ../greetings

require example/greetings v0.0.0-00010101000000-000000000000

Finall, we can run the code

wired% go run .
Hi, cakes. Welcome!

blog · about · resume · github · kde invent · endeavour · twitter · email · home

🚀❤️️🍰