go中import用于导入包。导入之后就可以使用包中的代码。
比如:

1
2
3
import(
    "fmt"
)

在代码中就可以使用fmt包中的方法,如:

1
fmt.Println("hello world")

1、使用点操作引入包时,可以省略包前缀:

1
2
3
import(
    . "fmt"
)

注意上面 fmt前多了 . 字符。代码中使用时:

1
Println("hello world")

前缀fmt就不需要了。

2、别名操作可以给包起个小名儿。如:

1
2
3
4
import(
"fmt"
)
f.Println("hello world")

3、_操作
由于go在引入包时调用包的init方法。所以使用_操作,主要是为了使用包的init函数,一般用在数据库方面的包中:

1
2
3
4
import (
    "database/sql"
    _ "github.com/ziutek/mymysql/godrv"
)

这个可以避免go编译时提示引入了包但未使用。

相关文章:

  • 2022-03-06
  • 2021-10-12
  • 2022-12-23
  • 2022-12-23
  • 2023-03-05
  • 2021-05-17
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-22
  • 2022-12-23
  • 2022-01-17
  • 2021-10-11
  • 2023-03-13
  • 2022-12-23
相关资源
相似解决方案