在不使用包名称的情况下调用包的函数? [英] Call a package's function without using its package name?

查看:43
本文介绍了在不使用包名称的情况下调用包的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

package "main"

import "fmt"

func main() {
    fmt.Println("hey there")
}

可以这样写:

package "main"

import blah "fmt"

func main() {
    blah.Println("hey there")
}

但是仍然有导入fmt来实现:

But is there anyway to import fmt to achieve:

package "main"

import "fmt" // ???

func main() {
    Println("hey there")
}

相比之下,

在C#中,您可以使用静态导入(例如using static System.Console)来完成此操作. Go中有可能吗?

In C# by contrast, you can do this by using a static import (e.g., using static System.Console). Is this possible in Go?

推荐答案

使用. (显性期)导入. 规范说:

Use the . (explicit period) import. The specification says:

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

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 main

import (
    . "fmt"
)

func main() {
    Println("Hello, playground")
}

不鼓励在Go社区中使用显式句点.点导入使程序更难以阅读,因为尚不清楚名称是当前程序包中还是导入的程序包中的程序包级标识符.

The use of the explicit period is discouraged in the Go community. The dot import makes programs more difficult to read because it's unclear if a name is a package-level identifier in the current package or in an imported package.

另一个选择是声明一个对该函数的引用的包级变量.使用类型别名来引用类型.

Another option is to declare a package-level variable with a reference to the function. Use a type alias to reference types.

 package main

import (
    "fmt"
)

var Println = fmt.Println

type ScanState = fmt.ScanState // type alias


func main() {
    Println("Hello, playground")
}

这篇关于在不使用包名称的情况下调用包的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆