douyasihefu6214 2012-10-17 00:27
浏览 9
已采纳

在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 Files.readAllLines etc without having Files imported.

  • 写回答

4条回答 默认 最新

  • doushen2154 2012-10-17 01:03
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?