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 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿