create Golang project with multiple returns

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
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值