go语言中的小技巧

2019-03-20  本文已影响0人  golang推广大使

在几种罕见的场景中需要使用括号来使代码编译正常。

package main

type T struct{x, y int}

func main() {
    // Each of the following three lines makes code fail to compile.
    // Some "{}" confuse compilers.
    /*
    if T{} == T{123, 789} {}
    if T{} == (T{123, 789}) {}
    if (T{}) == T{123, 789} {}
    var _ = func()(nil) // nil is viewed as a type
    */

    // We must add parentheses like the following two lines to
    // make code compile okay.
    if (T{} == T{123, 789}) {}
    if (T{}) == (T{123, 789}) {}
    var _ = (func())(nil) // nil is viewed as a value
}

两个errors.New函数使用同样的参数调用产生的两个error值并不相等

原因在于errors.New函数将会拷贝传入的字符串参数并使用一个指向这个拷贝的字符串指针作为返回的error值的动态值。两个不同的调用将会产生两个不同的指针

上一篇 下一篇

猜你喜欢

热点阅读