作为go菜鸟,最近在学习go语言,学到建立自建包并调用时,真的有暴捶电脑的感觉
step 1:
需要在goroot/src下加入自建包
(goroot就是go就是go语言环境下文件夹的路径)
如上图,这里放的是go提供的包,其中gopl.io就是我的自建包,结构如下:
conv.go
package tempconv
// CToF converts a Celsius temperature to Fahrenheit.
func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }
// FToC converts a Fahrenheit temperature to Celsius.
func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }
实现温度的转换
tempconv.go
package tempconv
import "fmt"
type Celsius float64
type Fahrenheit float64
const(
AbsoluteZeroC Celsius = -273.15
FreezingC Celsius = 0
BoilingC Celsius = 100
)
func (c Celsius) String() string {return fmt.Sprintf("%g°C", c)}
func (f Fahrenheit) String() string {return fmt.Sprintf("%g°F", f)}
大写表示可外部使用,提供公用变量和函数
step 2:在gopath中编写main函数
gopath就是项目目录:请看我的gopath结构:
main.go
package main
import(
"fmt"
"gopl.io/ch2/tempconv"
)
func main(){
fmt.Printf("Brrrr! %v\n", tempconv.AbsoluteZeroC) // "Brrrr! -273.15°C"
}
这时候如果我们在terminal直接运行,会有以下错误:
因此,我们需要在当前目录下建立一个go.mod
再次执行,它说我没有这个module,可能需要下载导入路径指定的包及其依赖项,然后安装命名包
于是:
最后,再次go run:
运行成功!