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  //就是没有结果输出