create Golang project with random

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值