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?
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With