creat Golang project with function

1, create new project "test1_function"

$ cd ~/project

$ mkdir test1_function

2, create new module for project "test1_function"

$ cd test1_function

$ mkdir main

$ mkdir pkg

3, initialize "main" folder

$ cd main

$ touch calculate.go

add following lines in "calculate.go"

package main

import (
	"fmt"
	"pkg"
)

func main() {
	fmt.Println("This is test1_function/main/calculate.go")
	var a, b int
	a = 3
	b = 4
	fmt.Println("3 + 4 = ", pkg.Add(a, b))
	fmt.Println("3 - 4 = ", pkg.Plus(a, b))
	fmt.Println("3 * 4 = ", pkg.Multiple(a, b))
	_a, _b, _err := pkg.Devide(a, b)
	fmt.Println("3 / 4 = ", _a, _b, _err)
	b = 0
	_a, _b, _err = pkg.Devide(a, b)
	fmt.Println("3 / 0 = ", _a, _b, _err)
}

4, initialize "pkg" folder

$ cd ../pkg

$ touch lib.go

add following lines in "lib.go"

package pkg

import "errors"

func Add(a, b int) int {
	return (a + b)
}

func Plus(a, b int) int {
	return (a - b)
}

func Multiple(a, b int) int {
	return (a * b)
}

func Devide(a, b int) (int, int, error) {
	if (b == 0) {
		return 0, 0, errors.New("Invalid deviden .")
	} else {
		return a/b, a%b, nil
	}
}

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 "test1_function"

$ cd ../main

$ go build calculate.go

you should find new binary file named "calculate" bellow folder "main"

$ ./calculate

you shoud get output:

     This is test1_function/main/calculate.go
     3 + 4 =  7
     3 - 4 =  -1
     3 * 4 =  12
     3 / 4 =  0 3 <nil>
     3 / 0 =  0 0 Invalid deviden .                                 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值