【问题标题】:Is it possible don't specify package name?是否可以不指定包名?
【发布时间】:2014-11-09 06:49:07
【问题描述】:

这是我的代码示例:

package main

import (
  "./bio"
)

func main() {
   bio.PeptideEncoding(genome, codonTable)
}

是否可以在不指定包名的情况下使用我的 paxkage (bio) 中的函数:

func main() {
   PeptideEncoding(genome, codonTable)
}

?

【问题讨论】:

    标签: go


    【解决方案1】:

    您可以使用 import declaration 之类的:

    . "./bio"
    

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

    这就是testing framework like govey does

    package package_name
    
    import (
        "testing"
        . "github.com/smartystreets/goconvey/convey"
    )
    
    func TestIntegerStuff(t *testing.T) {
        Convey("Given some integer with a starting value", t, func() {
            x := 1
    
            Convey("When the integer is incremented", func() {
                x++
    
                Convey("The value should be greater by one", func() {
                    So(x, ShouldEqual, 2)
                })
            })
        })
    }
    

    您不需要使用convey.So()convey.Convey(),因为导入以“.”开头。

    但不要滥用它,因为正如twotwotwo commentsstyle guide 不鼓励在测试之外使用它。

    除了这一种情况,不要在你的程序中使用import .
    它使程序更难阅读,因为不清楚像 Quux 这样的名称是当前包中的顶级标识符还是导入包中的顶级标识符。

    这就是我提到使用这种技术的测试框架的原因。


    作为Simon Whiteheadcommented,使用相对导入 通常不被认为是最佳实践(例如,请参阅“Go language package structure”)。

    你还应该通过GOPATH而不是相对导入包,如“Import and not used error”所示。

    【讨论】:

    猜你喜欢
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 2021-07-30
    相关资源
    最近更新 更多