简体   繁体   English

从选项进行变量声明

[英]Go variable declaration from options

I came across this is in node: 我在节点中遇到了这个:

var foo = bar || barfoofoo || foooobar;

How could I implement this in go. 我该如何实施呢?

Preamble 前言

I believe this practice is common in Javascript because of the desire to minimize the amount of code that is sent down the pipe. 我相信这种做法在Javascript中很常见,因为它希望尽量减少通过管道发送的代码量。 Using short-forms like that, relying on the truthy value of a string, makes it possible to write shorter code and save a couple of bytes. 依靠字符串的真实值,使用像这样的短格式可以编写较短的代码并节省几个字节。

However, this sort of practice is not type safe and is tricky: it involves expecting from every programmer reading your code that they know the truth value of the types in your language. 但是,这种做法不是类型安全的,并且很棘手:它涉及到每个阅读您的代码的程序员都希望他们知道您语言中类型的真实值。

I can see an argument for Javascript, but I believe that in most cases you should avoid this form. 我可以看到Javascript的论点,但我相信在大多数情况下,您应该避免使用这种形式。 Something similar is also used in C to verify null values. C中也使用类似的方法来验证空值。 But unless very idiomatic in the language you use, don't do that. 但是除非您使用的语言非常习惯,否则不要这样做。 Keep stuff simple-stupid. 保持简单愚蠢的东西。

To answer your question - how to do this in go. 要回答您的问题-如何进行。

Here's the trivial implementation: http://play.golang.org/p/EKTP8OsJmR 这是简单的实现: http : //play.golang.org/p/EKTP8OsJmR

bar := ""
barfoofoo := ""
foooobar := "omg"

var foo string
if bar != "" {
    foo = bar
} else if barfoofoo != "" {
    foo = barfoofoo
} else {
    foo = foooobar
}

fmt.Printf("foo=%s\n", foo)

Prints foo=omg . 打印foo=omg

Go is a type safe language. Go是一种类型安全的语言。 Strings don't have a boolean value, because they are not booleans: 字符串没有布尔值,因为它们不是布尔值:

http://play.golang.org/p/r7L8TYvN7c http://play.golang.org/p/r7L8TYvN7c

bar := ""
barfoofoo := ""
foooobar := "omg"

var foo string
if bar {
    foo = bar
} else if barfoofoo {
    foo = barfoofoo
} else {
    foo = foooobar
}

The compiler will yell at you: 编译器会对您大喊:

prog.go:12: non-bool bar (type string) used as if condition
prog.go:14: non-bool barfoofoo (type string) used as if condition

Otherwise, Go doesn't have a ternary operator , so you can't really do what you're trying: 否则, Go没有三元运算符 ,因此您无法真正执行所尝试的操作:

There is no ternary form in Go. Go中没有三元形式。 You may use the following to achieve the same result: 您可以使用以下方法获得相同的结果:

if expr {
    n = trueVal
} else {
    n = falseVal
}

Overall, you shouldn't do that, and you can't do that. 总的来说,您不应该那样做,也不能那样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM