go語言基礎之導入包的常用方法


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  //就是沒有結果輸出

  

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM