Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...