Simple Main#
Let create a simple main.go.
mkdir go-package-democd go-package-demotouch main.go
Update content of main.go and run it.
package mainimport "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 mainimport "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-demomkdir numbercd numbertouch 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 numberfunc GenerateNumber(n int) []int {var result []intfor i := 1; i <= n; i++ {result = append(result, i)}return result}
Finally let use the GenerateNumber in the number package for main.go.
package mainimport ("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)}