有条件地定义一个变量

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

Conditionally Define a Variable

问题

在JavaScript中,我们可以这样做:

var x = expr1 || expr2;

如果expr1不是undefined,它将被复制到x,如果它是undefined,则expr2将被复制到x。在Go语言中,我们可以使用以下方式:

var x string
if expr1 == "" {
    x = expr1
} else {
    x = expr2
}

是否有一种简写形式来实现这个功能?如果没有,为什么呢?

英文:

In javascript we can do this:

var x string = expr1 || expr2

If expr1 is not undefined, it will be copied to x, if it is undefined, expr2 will be copied to x. In go, we can use:

if expr1 == "" { var string x = expr1 } else { var string x = expr2 }

Is there are shorthand for this? If not, why?

答案1

得分: 4

我不知道关于“为什么”的原因,但你可以始终使用以下代码:

var a []string = expr1

if a == nil {
    a = expr2
}
英文:

I don't know about the "why" however you can always use this :

var a []string = expr1

if a == nil {
    a = expr2
}

答案2

得分: 4

《Go编程语言规范》

声明和作用域

声明将非空白标识符绑定到常量、类型、变量、函数、标签或包。程序中的每个标识符都必须声明。

零值

当通过声明或调用make或new来分配内存以存储一个值时,并且没有提供显式初始化,内存将被赋予默认初始化。这样的值的每个元素都被设置为其类型的零值:布尔类型为false,整数类型为0,浮点数类型为0.0,字符串类型为"",指针、函数、接口、切片、通道和映射类型为nil。

类型系统

静态类型检查

动态类型检查

英文:

> The Go Programming Language Specification
>
> Declarations and scope
>
> A declaration binds a non-blank identifier to a constant, type,
> variable, function, label, or package. Every identifier in a program
> must be declared.
>
> The zero value
>
> When memory is allocated to store a value, either through a
> declaration or a call of make or new, and no explicit initialization
> is provided, the memory is given a default initialization. Each
> element of such a value is set to the zero value for its type: false
> for booleans, 0 for integers, 0.0 for floats, "" for strings, and nil
> for pointers, functions, interfaces, slices, channels, and maps.


> Type system
>
> Static type-checking
>
> Dynamic type-checking


Go is a statically typed language. All variables must be declared at compile time and they have an well-defined initial value. JavaScript is a dynamically typed language. Variables are declared at run time. Therefore, the JavaScript construct makes no sense in Go.

huangapple
  • 本文由 发表于 2014年4月29日 23:48:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/23369433.html
匿名

发表评论

匿名网友

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

确定