1 在项目的src文件夹下,新建目录为 test_dir
2 目录下新建go文件,分别为hello.go与test_hello.go
代码为:
package test_pkg
import "fmt"
func PrintHello(){
fmt.Println("Hello, 我在 test_dir 目录下的 utils 包里")
}
package test_pkg
import "fmt"
func Test_pkg () {
fmt.Println("测试包的导入")
}
3 在上一级目录新建 main.go,代码:
package main
import (
"test_dir"
)
func main() {
test_pkg.PrintHello()
test_pkg.Test_pkg()
}
结果:
Hello, 我在 test_dir 目录下的 utils 包里
测试包的导入
总结:
- import 导入的是路径而不是包,导入目录后,可以使用这个目录下的所有包
- 调用方法时用包名,即go文件的pkg后定义的名称
- 出于习惯,包名和目录名通常会设置成一样
- 函数要大写才可以包外调用
- 项目要在gopath路径下
参考链接: