This is a creation in Article, where the information may have evolved or changed.
// 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")}
Output:
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
If you modify the import of Main.go for the following form:
// 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() //这已经将会提示编译失败}
Output:
C:/Go/bin/go.exe build -i [C:/Go/mycode/src/main]# main.\main.go:20: undefined: imp in imp.Print错误: 进程退出代码 2.
Preceded by _ description can only call Init.go inside the init () function, of course you can not display in Main.go inside call
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()}
Output:
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")