5.2 Go package and function

5.2 Go package and function

Call a function in multiple packages each other, need to use the knowledge Go package.

Code is organized as follows:

Ideas:

1.定义功能函数calc放入到utils.go,将utils.go放在utils文件夹/包中,当其他文件需要引入utils.go时,只需要导入该utils包,即可使用(包名.函数名)

Code

main.go

package main

import (
    "fmt"
    "gostudy/gobook/funcDemo/utils"
)

//两种方式二选一
//相对路径导入
//import "../utils"

//绝对路径导入,从src目录下开始

func main() {
    //通过utils包访问公开函数Calc
    res := utils.Calc(10, 20)
    fmt.Println(res)
}

utils.go

package utils

//写一个可导出的函数,需要首字母大写
//给返回值命名n3
func Calc(n1, n2 int) (n3 int) {
    res := n1 + n2
    return res
}

Import mode packets, see section 2.4

1.1 compiler executable program

The above code is compiled, the package needs to be declared as main, that is, package main, this is the syntax specification.

go build main.go

Guess you like

Origin www.cnblogs.com/open-yang/p/11256835.html
5.2
5.2