在go中导入软件包 [英] importing packages in go
问题描述
在编程语言中,为什么在导入一个包之后,我仍然必须在该包中添加一个包名称的方法?
ie
$ p $
importio / ioutil
func main(){
content,err = iotuil.ReadFile (somefile.txt)
// etc ..
}
这不是多余的吗?例如,在Java中,您可以在不导入任何文件的情况下执行Files.readAllLines等操作。
你真的可以回答你的问题,但如果你愿意,你可以实际调用这些方法,而不必明确声明这个包 - 只需在名称前加一个。
即可(但这是不建议;见下文):
package main
import(
。fmt
。io / ioutil
)
func main(){
content,err:= ReadFile(testfile)
if err != nil {
Println(Errors)
}
Println(My file:\\\
,string(content))
}
请注意下面的@ jimt的注释 - 这种做法在测试之外是 not ,因为它可能会导致名称冲突与未来的版本。此外,绝对同意@ DavidGrayson更好地阅读/查看事情来自哪里。
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.
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.
这篇关于在go中导入软件包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!