加载包内容后,不使用它们的名称。

huangapple go评论77阅读模式
英文:

Load package contents without using their name afterwards

问题

在Go语言中,没有直接的方法可以加载一个包的内容而不需要使用包名。Go语言鼓励显式导入和使用包名来访问包中的函数和变量。这样可以提高代码的可读性和可维护性。

如果你想要在Go中实现类似Python中的方式,可以使用以下方法:

  1. 使用包名导入:
    在Go中,你需要使用包名来导入包中的函数和变量。例如,如果你想要导入path/to/my/package包并访问其中的函数foo,你可以这样写:

    import "path/to/my/package"
    
    func main() {
        // 调用包中的函数foo
        package.foo()
    }
    
  2. 使用别名导入:
    如果你不想每次都使用完整的包名来访问函数和变量,你可以使用别名来简化代码。例如:

    import pkg "path/to/my/package"
    
    func main() {
        // 使用别名pkg来访问包中的函数foo
        pkg.foo()
    }
    

请注意,Go语言的设计哲学是鼓励显式导入和使用包名,这样可以提高代码的可读性和可维护性。因此,尽量遵循这种方式来编写Go代码。

英文:

Is there a way to load the contents of a package in go without needing to use the package name? For example, in Python you can do:

from somepackage import *
# access function from somepackage foo
foo()

I would like to do that in Go. I tried:

import _ "path/to/my/package"

but it didn't work. I'm having trouble articulating myself to find the solution online, if there is one.

答案1

得分: 5

《Go编程语言规范》

导入声明

如果出现一个显式的句点(.)而不是一个名称,那么该包的所有在该包的包块中声明的导出标识符将被声明在导入源文件的文件块中,并且必须在没有限定符的情况下访问。

使用句点(.)代替名称。例如,

package main

import (
	"fmt"
	. "time"
)

func main() {
	fmt.Println(Now()) // time.Now()
}

输出:

2009-11-10 23:00:00 +0000 UTC
英文:

> The Go Programming Language Specification
>
> Import declarations
>
> If an explicit period (.) appears instead of a name, all the package's
> exported identifiers declared in that package's package block will be
> declared in the importing source file's file block and must be
> accessed without a qualifier.

Use a period (.) instead of a name. For example,

package main

import (
	"fmt"
	. "time"
)

func main() {
	fmt.Println(Now()) // time.Now()
}

Output:

2009-11-10 23:00:00 +0000 UTC

huangapple
  • 本文由 发表于 2016年2月20日 10:52:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/35518548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定