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.
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.
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.
You cannot import the main package. Any shared code should go in a separate package, which can be imported by main (and other packages).
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.
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.
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