Menu
Coddy logo textTech

Go Workspace & Modules

Part of the Object Oriented Programming section of Coddy's GO journey — lesson 2 of 107.

A Go module is a collection of related Go files. The go.mod file at the root of your project declares the module name and Go version.

Initialize a module with the terminal command

go mod init myapp

This creates a go.mod file

module myapp

go 1.21

A simple project structure

myapp/
├── go.mod
├── main.go
└── helper.go

All files share the same package

// helper.go
package main

func Double(n int) int {
    return n * 2
}
// main.go
package main

import "fmt"

func main() {
    result := Double(5)
    fmt.Println(result) // Output: 10
}

The go.mod file defines your project as a module. All .go files declaring the same package can access each other's functions directly. The module name in go.mod identifies your project.

challenge icon

Challenge

Easy

Complete mathhelper.go within the same module and package:

  • Double — returns n * 2
  • Triple — returns n * 3
  • Square — returns n * n

Cheat sheet

A Go module is a collection of related Go files declared by a go.mod file at the project root.

Initialize a module:

go mod init myapp

This creates a go.mod file:

module myapp

go 1.21

All .go files in the same package can access each other's functions directly:

// helper.go
package main

func Double(n int) int {
    return n * 2
}
// main.go
package main

import "fmt"

func main() {
    result := Double(5)
    fmt.Println(result) // Output: 10
}

Try it yourself

package main

import "fmt"

func main() {
    var n int
    fmt.Scan(&n)

    fmt.Printf("Double: %d\n", Double(n))
    fmt.Printf("Triple: %d\n", Triple(n))
    fmt.Printf("Square: %d\n", Square(n))
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming