在一些源代码中我发现了这个:
if etherbase != (common.Address{}) {
return etherbase, nil
}
Run Code Online (Sandbox Code Playgroud)
etherbase是类型common.Address,它被定义为:
// Lengths of hashes and addresses in bytes.
const (
HashLength = 32
AddressLength = 20
)
// Address represents the 20 byte address of an Ethereum account.
type Address [AddressLength]byte
Run Code Online (Sandbox Code Playgroud)
问题是:在这种情况下,parethesis意味着什么?为什么不能省略它们?像这样:
if etherbase != common.Address{} {
return etherbase, nil
}
Run Code Online (Sandbox Code Playgroud)
pet*_*rSO 10
当使用LiteralType的TypeName形式的复合文字作为关键字与"if","for"或"switch"语句块的左括号之间的操作数出现时,会出现解析歧义,并且复合文字是未括在括号,方括号或花括号中.在这种罕见的情况下,文字的左括号被错误地解析为引入语句块的那个.要解决歧义,复合文字必须出现在括号内.
Run Code Online (Sandbox Code Playgroud)if x == (T{a,b,c}[i]) { … } if (x == T{a,b,c}[i]) { … }
块common.Address{}之前的模糊复合文字.if{ … }
if etherbase != common.Address{} {
return etherbase, nil
}
Run Code Online (Sandbox Code Playgroud)
块{...} (common.Address{})之前的明确复合文字if.
if etherbase != (common.Address{}) {
return etherbase, nil
}
Run Code Online (Sandbox Code Playgroud)
例如,
package main
const AddressLength = 20
type Address [AddressLength]byte
func f(etherbase Address) (Address, error) {
// Unambiguous
if etherbase != (Address{}) {
return etherbase, nil
}
return Address{}, nil
}
func g(etherbase Address) (Address, error) {
// Ambiguous
if etherbase != Address{} {
return etherbase, nil
}
return Address{}, nil
}
func main() {}
Run Code Online (Sandbox Code Playgroud)
游乐场:https://play.golang.org/p/G5-40eONgmD