有条件地定义一个变量

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?

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

var a []string = expr1

if a == nil {
    a = expr2
}

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.