dsf11t5u1651 2019-05-07 07:27
浏览 11
已采纳

golang中有“使用”吗? [重复]

This question already has an answer here:

Is there a way to use the names in a golang import without specifying the package name each time? In C++ I can "use" a nampespace. In Java, when I import something, the namespace is automatically used.

Sometimes I have a high level helper library, who's main purpose is using another pacakge, and providing some high level wrappers for it. It seems overly verbose to keep using the pacakge name over and over in the code.

package myhighlevellibrary
import "mypackage"

func Foo() *mypackage.SomeType{
  a:=mypackage.Somefunction();
  b:=mypackage.SomeFactoryMethod(a);
  return b
}

Can I somehow avoid writing the "mypackage" literal so many times in my code? It gets much worse as my library grows larger...

</div>
  • 写回答

1条回答 默认 最新

  • dream07769 2019-05-07 07:32
    关注

    This is possible using the "dot" import. Use the . as the package name in the import declaration, and so you can refer to the package's exported identifiers as if they would have been declared in the package you import them.

    Quoting from Spec: 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.

    This is how your example would look like:

    package myhighlevellibrary
    
    import . "mypackage"
    
    func Foo() *SomeType {
        a := Somefunction()
        b := SomeFactoryMethod(a)
        return b
    }
    

    Here's a runnable Playground example:

    package main
    
    import (
        . "fmt"
        . "reflect"
    )
    
    func main() {
        Println(TypeOf("text")) // short for: fmt.Println(reflect.TypeOf("text"))
    }
    

    See related / possible duplicate: What's C++'s `using` equivalent in golang

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?