Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/12925450/in-go-how-to-import-function-directly-without-need-to-prefix-with-the-package

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:
", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...