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

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

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

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答