1, create new project "test2_random"
$ cd ~/project
$ mkdir test2_random
2, create new module for project "test2_random"
$ cd test2_random
$ mkdir main
$ mkdir pkg
3, initialize "main" folder
$ cd main
$ touch magic.go
add following lines in "magic.go"
package main
import (
"fmt"
"pkg"
)
func main() {
fmt.Println("This is test2_random/main/magic.go")
n, err := pkg.MagicNum()
if (err == nil) {
fmt.Println("Your number is ", n)
} else {
fmt.Println("Sorry,", err)
}
}
4, initialize "pkg" folder
$ cd ../pkg
$ touch randomNum.go
add following lines in "randomNum.go"
package pkg
import (
"time"
"errors"
"math/rand"
)
func MagicNum() (int, error) {
var nums = []int{122, 233, 344, 455, 566, 677, 788, 899, 900}
rand.Seed(time.Now().UnixNano())
var idx int = rand.Intn(len(nums))
if (nums[idx] % 3 == 0) {
return nums[idx], nil
} else {
return 0, errors.New("there is no number for you.")
}
}
5, configure folder "main" and "pkg"
$ cd ../main
$ go mod init main
you will get new file named "go.mod" bellow folder "main", edit it with following lines
module main
go 1.15
require "pkg" v0.0.0
replace "pkg" => "../pkg"
$ cd ../pkg
$ go mod init pkg
you will get new file named "go.mod" bellow folder "pkg", it has following lines
module pkg
go 1.15
6, compile main function for project "test2_random"
$ cd ../main
$ go build magic.go
you should find new binary file named "magic" bellow folder "main"
$ ./magic
you shoud get output:
Example 1
This is test2_random/main/magic.go
Sorry, there is no number for you.
Example 2
This is test2_random/main/magic.go
Your number is 900