英文:
Any way to alias a function name to '_'?
问题
在Go语言中,是否有任何情况下可以使用gettext的简写形式:
_("要翻译的字符串。")
我相当确定答案是“否”,但还是问一下,以防我忽略了什么。我认为最好的方法是:
import . "path/to/gettext-package"
...
s := gettext("要翻译的字符串。")
因为下划线在Go语言中有特定的含义,尝试定义一个名为“_”的函数会导致编译时错误“无法使用_作为值”。
英文:
In Go, is there any circumstance where the gettext short-form of:
_("String to be translated.")
can be used? One of those times where I'm fairly certain the answer is 'no', but asking just in case I've overlooked something. I'm thinking the best that can be achieved is:
import . "path/to/gettext-package"
...
s := gettext("String to be translated.")
since underscore has a very specific meaning, and attempting to define a function named '_' results in the compile-time error "cannot use _ as value".
答案1
得分: 15
不。空白标识符不会引入新的绑定。
也就是说,你可以声明名为_
的“东西”,但是不能使用该“名称”来引用它们。
然而,你可以接近目标:
package main
import "fmt"
var p = fmt.Println
func main() {
p("Hello, playground")
}
(也可以在这里找到)
也就是说,你可以将任何(本地或导入的)函数绑定到一个变量上,然后通过该变量调用函数,从而摆脱包前缀 - 如果你认为这很方便的话。在我看来,不是很方便。
英文:
No. The blank identifier
> ... does not introduce a new binding.
IOW, you can declare "things" named _
but you cannot refer to them in any way using that "name".
However, one can get close to the goal:
package main
import "fmt"
var p = fmt.Println
func main() {
p("Hello, playground")
}
(also here)
ie. you can bind any (local or imported) function to a variable and later invoke the function through that variable, getting rid of the package prefix - if you think that's handy. IMO not, BTW.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论