1.包存在哪里?

看段代码,想必大家都知道GoPath和GoRoot的是什么了。(GoPath = 你的工作空间路径 ,GoRoot = Go的安装路径)

func init() {
	fmt.Printf("Go Root %s \n", os.Getenv("GOROOT"))
	// Go Root /usr/local/Cellar/go/1.14/libexec
	fmt.Printf("Go Path %s \n", os.Getenv("GOPATH"))
	// Go Path /Users/logan/go
}

通过 . 对 “fmt” 进行别名,则不需要使用 fmt.Printf("...")了,但一个包中只能有一个.别名否则会报错。同时可以配置多个GoPath用 : 分割,例如 GOPATH=/Users/logan/go:~/myworkspace

2.扫描包的顺序?

import (
  "fmt" 
  "net/http" 
) 

如果搜索net/http包时,搜索顺序如下:

/usr/local/Cellar/go/1.14/libexec/src/net/http 
/Users/logan/go/src/net/http 
~/myworkspace/src/net/http

3.包的导入顺序?及var、const、init()加载顺序。

包导入顺序如图所示,同时可知先初始化const、其次为var、之后为init(),注意同时可以有多个init方法,从上到下依次执行。

img

4.包重名了怎么办?

import (
   "runtime"
   "strings"
	 strings2 "strings"
   "testing"
)

func TestImport(t *testing.T){
   strings.PrintlnHello("Logan")
   strings2.Compare("a","b")
}

如果包重名了,只能起别名,否则不能识别出是哪个包中的方法需要引用。

5.包导入的”奇淫技巧“

_导入 及 远程包

_ "github.com/go-sql-driver/mysql" // 导入mysql驱动

仅需要依赖执行github.com/go-sql-driver/mysql中的初始化init()函数

  1. 编译期加载

    var (
      // 常量,数值、字符(runes)、字符串或布尔值等
       i = 1<<3 
    )
    
  2. 运行期加载,如:

    math.Sin(math.Pi/4)
    

参考连接:

  1. https://www.cnblogs.com/f-ck-need-u/p/9847554.html