Golang: Import Local Packages


Create new directory and initial go module

mkdir mygoproject && cd mygoproject

go mod init mygotest

 
where mygotest is our module name, can be like github.com/user/mygotest


Create main file and package lucky

mkdir lucky && touch lucky/random.go

 

Create lucky/random.go file
package lucky

import "math/rand"

func LuckyNumber() int {
    return rand.Intn(100)
}

 

Create main.go file
package main

import (
    "fmt"
    "mygotest/lucky"
)

func main() {
    fmt.Println("Your lucky number is:", lucky.LuckyNumber())
}

 

Run go

go run main.go

 

Go project structure

Read here https://github.com/golang-standards/project-layout?tab=readme-ov-file