Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a package's function without using its package name?

Tags:

go

Example:

package "main"

import "fmt"

func main() {
    fmt.Println("hey there")
}

Could be written:

package "main"

import blah "fmt"

func main() {
    blah.Println("hey there")
}

But is there anyway to import fmt to achieve:

package "main"

import "fmt" // ???

func main() {
    Println("hey there")
}

In C# by contrast, you can do this by using a static import (e.g., using static System.Console). Is this possible in Go?

like image 513
tarrball Avatar asked Dec 23 '17 16:12

tarrball


1 Answers

Use the . (explicit period) import. The specification says:

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.

Example:

package main

import (
    . "fmt"
)

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

The use of the explicit period is discouraged in the Go community. The dot import makes programs more difficult to read because it's unclear if a name is a package-level identifier in the current package or in an imported package.

Another option is to declare a package-level variable with a reference to the function. Use a type alias to reference types.

 package main

import (
    "fmt"
)

var Println = fmt.Println

type ScanState = fmt.ScanState // type alias


func main() {
    Println("Hello, playground")
}
like image 188
Bayta Darell Avatar answered Sep 23 '22 06:09

Bayta Darell