// main project main.go
package main
import (
"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 imp
import (
"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 = 13
skip = 1, pc = 4366150, file = C:/Go/src/runtime/proc.go, line = 185
skip = 2, pc = 4513537, file = C:/Go/src/runtime/asm_amd64.s, line = 2197
Hello World! in package imp
如果修改 main.go 的 import 为一下形式:
// main project main.go
package main
import (
"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.go
package main
import (
"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")
有疑问加站长微信联系(非本文作者)