1、導入包
示例: 法一
package main //導入包,必須使用,否則編譯不過 import "fmt" import "os" func main() { fmt.Println("this is a test") fmt.Println("os.Args = ", os.Args) }
執行結果:
this is a test os.Args = [D:\GoFiles\src\hello_01\hello_01.exe]
示例: 法二 在()中間直接加包名
package main //導入包,必須使用,否則編譯不過 //推薦用法 import ( "fmt" "os" ) func main() { fmt.Println("this is a test") fmt.Println("os.Args = ", os.Args) }
執行結果:
this is a test os.Args = [D:\GoFiles\src\hello_01\hello_01.exe]
示例3: 調用函數,無需通過包名
package main import . "fmt" //調用函數,無需通過包名 import . "os" //容易導致變量重名操作 func main() { Println("this is a test") Println("os.Args = ", Args) }
執行結果:
this is a test os.Args = [D:\GoFiles\src\hello_01\hello_01.exe]
示例4:給包取別名
package main //給包取別名 import io "fmt" func main() { io.Println("this is a test") }
執行結果:
this is a test
示例5: _操作, 忽略此包
有時,用戶可能需要導入一個包,但是不需要引用這個包的標識符。在這種情況,可以使用空白標識符_來重命名這個導入:
_操作其實是引入該包,而不直接使用包里面的函數,而是調用了該包里面的init函數。
package main //忽略此包 import _ "fmt" func main() { }
#執行結果:
null //就是沒有結果輸出