go - golang中有 "using"吗?

标签 go

<分区>

有没有一种方法可以在 golang 导入中使用名称而无需每次都指定包名称? 在 C++ 中,我可以“使用”命名空间。 在 Java 中,当我导入某些东西时,会自动使用命名空间。

有时我有一个高级助手库,其主要目的是使用另一个包,并为其提供一些高级包装器。在代码中反复使用 pacakge 名称似乎过于冗长。

package myhighlevellibrary
import "mypackage"

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

我能否以某种方式避免在我的代码中多次写入“mypackage”文字?随着我的图书馆越来越大,情况变得更糟......

最佳答案

这可以使用“点”导入来实现。使用 . 作为导入声明中的包名称,因此您可以引用包的导出标识符,就好像它们已在您导入它们的包中声明一样。

引自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.

这就是您的示例的样子:

package myhighlevellibrary

import . "mypackage"

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

这是一个可运行的 Playground example :

package main

import (
    . "fmt"
    . "reflect"
)

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

查看相关/可能的副本:What's C++'s `using` equivalent in golang

关于go - golang中有 "using"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56017558/

相关文章:

go - Go中的Os Exec Sudo命令

go - 无法在 golang 的 http2 中使用流式传输

go - 如何检查go文件中是否存在函数

Golang - 处理需要泛型类型的情况

python - Go 真的能比 Python 快那么多吗?

go - 将 go get 命令更新我本地机器上的包

去原子加载和存储

goroutine channel & WaitGroup fatal error : all goroutines are asleep - deadlock

google-app-engine - 对 Google App Engine Go 运行时的搜索支持

pointers - 对指针 slice 的反射(reflection)