Simple Main#

Let create a simple main.go.

mkdir go-package-demo
cd go-package-demo
touch main.go

Update content of main.go and run it.

package main
import "fmt"
func main() {
fmt.Println("Hello Hai")
}

Let run it.

go run main.go

Simple Module#

Module to manage dependencies such as third party packages. Let create a module

go mod init entest/package-demo

This command will generate a go.mod file which manage dependencies, for example, let use a rsc.io/quote in main.go

package main
import "fmt"
import "rsc.io/quote"
func main() {
fmt.Println("Hello Hai")
fmt.Println(quote.Go())
}

To update and download dependencies, let run go mod tidy command.

go mod tidy

Then we can run the main.go as usually.

go run main.go

Simple Package#

By default, we already have main package with main.go. Let create another package called number.

cd go-package-demo
mkdir number
cd number
touch random.go

Let set the update project structure.

|--go-package-demo
|--number
|--random.go
|--go.mod
|--go.sum
|--main.go

Content of number/random.go.

package number
func GenerateNumber(n int) []int {
var result []int
for i := 1; i <= n; i++ {
result = append(result, i)
}
return result
}

Finally let use the GenerateNumber in the number package for main.go.

package main
import (
"entest/package-demo/number"
"fmt"
"rsc.io/quote"
)
func main() {
fmt.Println("Hello Hai")
fmt.Println(quote.Go())
x := number.GenerateNumber(10)
fmt.Println(x)
}

Multiple Module#