import 导包

有相对路径 和 绝对路径,推荐使用绝对路径。
GoLand 中导包如果不用,会报错。

格式

导入单个路径

1
import "./model"  //不建议这种方式import

导入多个路径

1
2
3
4
import (
"./model"
"github.com/forfreeday/go-learning"
)

路径

相对路径:

1
import "./model"  //不建议这种方式import

绝对路径:

1
import "shorturl/model"  //加载GOPATH/src/shorturl/model模块

点操作

这个点操作的含义就是这个包导入之后在你调用这个包的函数时,你可以省略前缀的包名,

1
2
3
4
5
6
7
import( . "fmt" )

func main() {
fmt.Println("hello world")
//可以省略的写成
Println("hello world")
}

别名

1
2
3
4
5
6
7
import(test "fmt")

func main() {
var a int = 10;
test.Print("a address is % :", &a)
pointer.Add(1,2)
}

_ 执行init

作用:当导入一个包时,该包下的文件里所有init()函数都会被执行,
使用下划线_导的包,不使用也不报错

如:import _ hello/imp

场景:
有些时候我们并不需要把整个包都导入进来,仅仅是是希望它执行init()函数而已。
这个时候就可以使用 import _引用该包,即使用import _ 包路径只是引用该包,仅仅是为了调用init()函数,所以无法通过包名来调用包中的其他函数。

目录结构

1
2
3
4
5
6
>--src
> |
> |--main.go
> \--hello
> \--imp
> |--init.go

验证初始化

这里可以执行 init(),但是不能调用这个包内的函数。

1
2
3
4
5
6
package main
import _ "hello/imp"

func main() {
// imp.Print() 编译报错,说:undefined: imp
}
1
2
3
4
5
6
7
8
9
10
package imp
import "fmt"

func init() {
fmt.Println("imp-init() come here.")
}

func Print() {
fmt.Println("Hello!")
}

输出结果:imp-init() come here.

如果需要即要初始化 init() 函数,又要调用其他函数,就必须再导入一次不带下划线的包就可以。

总结

go 的 import,还是比较中规中规矩,实际使用当中 import() 使用的比较多,毕竟不会只导入一两个包。
_ 的用法在很多框架低层中很常用,要注意。

项目练习代码: https://github.com/forfreeday/go-learning