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 .