Import everything from a package

2020-02-29 06:39发布

问题:

I'm wondering if there is any way to import the full contents of a package so that I don't have to prefix calls to things in the package with a package name?

For example, is there a way to replace this:

import "fmt"
func main() {
    fmt.Println("Hello, world")
}

with this:

import "fmt"
func main() {
    Println("Hello, world")
}

回答1:

The Go Programming Language Specification

Import declarations

If an explicit period (.) appears instead of a name, all the package's exported identifiers declared in that package's package block will be declared in the importing source file's file block and must be accessed without a qualifier.


For example,

package main

import . "fmt"

func main() {
    Println("Hello, world")
}

Playground: https://play.golang.org/p/xl7DIxxMlU5

Output:

Hello, world


标签: go package