1, create new project “test3_multiple”
$ cd ~/project
$ mkdir test3_multiple
2, create new module for project “test3_multiple”
$ cd test3_multiple
$ mkdir main
$ mkdir pkg
3, initialize “main” folder
$ cd main
$ touch multiple.go
add following lines in “multiple.go”
package main
import (
"log"
"pkg"
)
func main() {
var nameList = []string{"pang pang", "nao nao", "biu biu", "zai zai"}
var greetList map[string]string = pkg.Greeting(nameList)
for _, content := range greetList {
log.Println(content)
}
}
4, initialize “pkg” folder
$ cd ../pkg
$ touch lib.go
add following lines in “lib.go”
package pkg
import (
"fmt"
"time"
"math/rand"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func greet(name string) string {
var greetFormat = []string{"Hello, %s", "How are you, %s", "Nice day, %s"}
return fmt.Sprintf(greetFormat[rand.Intn(len(greetFormat))], name)
}
func Greeting(names []string) map[string]string {
var gList = make(map[string]string)
for _, n := range names {
gList[n] = greet(n)
}
return gList
}
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 “test3_multiple”
$ cd ../main
$ go build multiple.go
you should find new binary file named “multiple” bellow folder “main”
$ ./multiple
Example 1
2020/12/19 21:05:17 Nice day, pang pang
2020/12/19 21:05:17 Nice day, nao nao
2020/12/19 21:05:17 Hello, biu biu
2020/12/19 21:05:17 Hello, zai zai
Example 2
2020/12/19 21:05:21 Hello, nao nao
2020/12/19 21:05:21 How are you, biu biu
2020/12/19 21:05:21 How are you, zai zai
2020/12/19 21:05:21 Nice day, pang pang