遮蔽全局函数

huangapple go评论85阅读模式
英文:

Shadowing a global function

问题

有没有办法在golang包的全局范围内隐藏一个函数?在某个go文件中,我不希望用户能够调用BFunc...也就是说,我想对它进行包装...

假设这个包提供了BFunc()函数,我有一个调皮的用户想要导入它:

. "github.com/a/bfunc"

所以,在另一个go文件的全局范围内,我可能会这样做:

func BFunc() { fmt.Print("哈哈,我骗到你了") }

当我尝试这样做时,我会得到一个错误,指出有一个相同函数的先前声明,特别是指.导入。

有没有一种语法上的技巧可以阻止用户将bfunc.BFunc()方法全局导入到他们的代码中?

更新

可以使用一个更简单的代码片段来描述这个问题。

package main
import . "fmt"
func Print(t string) { 
   Print("ASDF")
}
func main() {
    Print("ASDF")
}

这段代码无法工作,因为Print被重新声明了。如果有一种方法可以绕过这个问题,使得Print可以重新声明,那么这将有效地回答了我的原始问题。

英文:

Is there a way to shadow a function at global scope in a golang package? In some go file, I DONT want users to be able to call BFunc... That is, I want to wrap it...

// Lets say this package provides BFunc() 
// And I have a naughty user who wants to import it
. "github.com/a/bfunc"

So, In another go file at global scope, I might do:

func BFunc() { fmt.Print("haha I tricked you") }

When I try this, I get an error that there is a previous declaration of the same function, referring specifically to the . import.

Would there be a syntactical hack I can do to prevent users from globally importing the bfunc.BFunc() method into their code?

UPDATE

This can be described using a simpler snippet.

package main
import . "fmt"
func Print(t string) { 
   Print("ASDF")
}
func main() {
    Print("ASDF")
}

Which doesn't work, because Print is redeclared. If there is a way to hack around this so that Print can be redeclared, then that would answer my original question effectively.

答案1

得分: 2

如果你不希望库的用户使用某个函数,那就不要导出该函数。

无法遮蔽另一个包中定义的标识符。即使在同一个包中,也无法遮蔽命名函数。

英文:

If you don't want users of a library to use a function, then don't export that function.

Shadowing identifiers defined in another package is impossible. Shadowing named functions is impossible even in the same package.

huangapple
  • 本文由 发表于 2016年3月2日 06:02:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/35734475.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定