Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Go, how to import function directly, without need to prefix with the package name when I call it?

Tags:

go

In the Go programming language, why after importing a package do I still have to prefix a method within that package with the package name?

i.e.

import "io/ioutil"  func main() {      content, err = iotuil.ReadFile("somefile.txt")     // etc.. } 

Isn't this redundant? In Java, for example, you can do things like importing Files.readAllLines etc without having Files imported.

like image 596
Steve Avatar asked Oct 17 '12 00:10

Steve


People also ask

How do I import a package into Go?

To import a package, we use import syntax followed by the package name. đź’ˇ Unlike other programming languages, a package name can also be a subpath like some-dir/greet and Go will automatically resolve the path to the greet package for us as you will see in the nested package topic ahead.

Which keyword is used to import packages in a Go program?

The keyword “import” is used for importing a package into other packages. In the Code Listing -1, we have imported the package “fmt” into the sample program for using the function Println. The package “fmt” comes from the Go standard library.

Can we import main package in Golang?

You cannot import the main package. Any shared code should go in a separate package, which can be imported by main (and other packages).

How do I import multiple packages in Go?

2. Grouped import. Go also supports grouped imports. This means that you don't have to write the import keyword multiple times; instead, you can use the keyword import followed by round braces, (), and mention all the packages inside the round braces that you wish to import.


1 Answers

I guess this doesn't really answer your question, but if you want, you can actually call the methods without explicitly stating the package - just import with a . in front of the names (but this is not recommended; see below):

package main  import (   . "fmt"   . "io/ioutil" )  func main () {   content, err := ReadFile("testfile")   if err != nil {     Println("Errors")   }   Println("My file:\n", string(content)) } 

Note @jimt's comment below - this practice is not advised outside of tests as it could cause name conflicts with future releases. Also, definitely agree with @DavidGrayson's point of being nicer to read/see where things come from.

like image 102
RocketDonkey Avatar answered Oct 06 '22 00:10

RocketDonkey