Learning Go from Documentation #2 (Call your code from another module)

Kuzey Köse
3 min readDec 23, 2021

Creating simple module that can reachable another module is this blogs tasks.

Go code is grouped into packages, and packages are grouped into modules.

Let’s start with creating a Go module. Quickly, open the terminal (I use macOS), and write these commands. These create a folder and import a ‘go.mod’ file. You can reach all steps with Learning Go from Documentation #1.

$ mkdir greetings
$ cd greetings
$ go mod init example.com/greetings
$ touch greetings.go

then open this folder in any editor you like. I prefer VSCode. Select the greetings.go file and edit it with our first function.

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

Let’s talk about what we write. Describing functions is easy. func keyword identifies the function, then function name follows this keyword, in our function names is Hello. In parenthesis, functions take parameters and parameters type, and then return type follows these parentheses.

Also, we need to attention to the declaration operation :=, this is a shortcut for initializing a variable. In a long way, we need to use the var keyword. For example;

var message string
message = ftm.Sprintf("Hi, %v. Welcom!", name)

We import the ftm package using Sprintf function. Shortly, it changes %v to the name which comes from functions parameters, and returns manipulated string like “Hi, Kuzey. Welcome!”.

Let’s create another module and call our first function Hello. At the beginning of the blog, we create a folder and go files. We need to do it one more time but in a different folder.

// terminal
$ cd ..
$ mkdir hello
$ cd hello
$ go mod init example.com/hello
$ touch hello.go

then open the hello.go file and type down code like this. We learn what is function and what is declaration operator. So, easily we can understand this.

// hello.go
package main
import (
"fmt"
"example.com/greetings"
)
func main() {
message := greetings.Hello("Kuzey")
fmt.Println(message)
}

BUT! we have a little problem with “example.com/greetings”. This is because we don’t publish our package. If we are, Go tools could find it to download it. But our code is on our local file system. We need to describe where is the greeting package is in the local. “go mod edit” command helps us describe where it is.

// terminal
$ go mod edit -replace example.com/greetings=../greetings
$ go mod tidy

and run the go function!

// terminal
$ go run .
Hi, Kuzey. Welcome!

This blog post is personal notes 🙂 If you are more interested in it, you need to check, https://go.dev/doc/tutorial/create-module, https://go.dev/doc/tutorial/call-module-code

--

--