這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
// main project main.gopackage mainimport ("fmt"//_ "main/hello/imp""main/hello/imp""runtime")func main() {for skip := 0; ; skip++ {pc, file, line, ok := runtime.Caller(skip)if !ok {break}fmt.Printf("skip = %v, pc = %v, file = %v, line = %v\n", skip, pc, file, line)}imp.Print()}
package impimport ("fmt")func init() {fmt.Println("imp-init come here.")}func Print() {fmt.Println("Hello World! in package imp")}
輸出:
imp-init come here.skip = 0, pc = 4762118, file = C:/Go/mycode/src/main/main.go, line = 13skip = 1, pc = 4366150, file = C:/Go/src/runtime/proc.go, line = 185skip = 2, pc = 4513537, file = C:/Go/src/runtime/asm_amd64.s, line = 2197Hello World! in package imp
如果修改 main.go 的 import 為一下形式:
// main project main.gopackage mainimport ("fmt"_ "main/hello/imp" //這裡前面加上了 _//"main/hello/imp""runtime")func main() {for skip := 0; ; skip++ {pc, file, line, ok := runtime.Caller(skip)if !ok {break}fmt.Printf("skip = %v, pc = %v, file = %v, line = %v\n", skip, pc, file, line)}imp.Print() //這已經將會提示編譯失敗}
輸出:
C:/Go/bin/go.exe build -i [C:/Go/mycode/src/main]# main.\main.go:20: undefined: imp in imp.Print錯誤: 進程結束代碼 2.
前面加上了 _ 說明只能調用 init.go 裡面的 init() 函數, 當然你不能顯示的在 main.go 裡面調用
imp.init()
// main project main.gopackage mainimport ("fmt"_ "main/hello/imp"//"main/hello/imp""runtime")func main() {for skip := 0; ; skip++ {pc, file, line, ok := runtime.Caller(skip)if !ok {break}fmt.Printf("skip = %v, pc = %v, file = %v, line = %v\n", skip, pc, file, line)}imp.init()//imp.Print()}
輸出:
C:/Go/bin/go.exe build -i [C:/Go/mycode/src/main]# main.\main.go:19: undefined: imp in imp.init錯誤: 進程結束代碼 2.
---------------------------------------------------------------------------------------------------
import(. "fmt") 這個點操作的含義就是這個包匯入之後在你調用這個包的函數時,你可以省略首碼的包名,也就是前面你調用的fmt.Println("hello world") 可以省略的寫成Println("hello world")import(f "fmt") 別名操作調用包函數時首碼變成了重新命名的首碼,即f.Println("hello world")