0在golang中是什么意思

0在golang中是什么意思

本文介绍了*(* int)(nil)= 0在golang中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到函数

I notice there is one line *(*int)(nil) = 0 in function throw

//go:nosplit
func throw(s string) {
    // Everything throw does should be recursively nosplit so it
    // can be called even when it's unsafe to grow the stack.
    systemstack(func() {
        print("fatal error: ", s, "\n")
    })
    gp := getg()
    if gp.m.throwing == 0 {
        gp.m.throwing = 1
    }
    fatalthrow()
    *(*int)(nil) = 0 // not reached
}

*(* int)(nil)= 0 是什么意思?并且由于无法到达此行 *(* int)(nil)= 0 ,为什么在这里?有什么特殊用途吗?

What does *(*int)(nil) = 0 means? and since this line *(*int)(nil) = 0 could NOT be reached, why it is here? any special usage?

推荐答案

该行:

*(*int)(nil) = 0

尝试取消引用 nil 指针并为其分配值,这始终是运行时的恐慌.该代码永远都不会到达此行,但是如果仍然会发生(例如,将来发生错误的代码更改),它将惊慌失措,因此可以检测到该错误,并且不会被忽略.

Tries to dereference a nil pointer and assign a value to it, which is always a runtime panic. The code should not reach this line, ever, but if it would anyhow (e.g. a faulty code change in the future), it would panic so the error could be detected and wouldn't go unnoticed.

在代码中也做类似的事情是常识,但是在代码中有一个更明显的"construct".例如 panic("unreachable").例如:

It's common sense to do something similar in your code too, but with a more obvious "construct" such as panic("unreachable"). For example:

func sign(a int) string {
    switch {
    case a > 0:
        return "Positive"
    case a < 0:
        return "Negative"
    case a == 0:
        return "Zero"
    default:
        panic("unreachable")
    }
}

请注意,在此示例中,这不仅是要及早发现错误,也是一个要求,因为对于编译器而言,无法保证将返回return语句.您还可以将 panic("unreachable"))语句移至 switch (而不是 default 分支)之后,

Note that in this example this is not just to detect errors early, it's also a requirement because to the compiler there would be no guarantee that a return statement would be reached. You could also move the panic("unreachable") statement after the switch (instead of the default branch), it's a matter of taste.

如果您将上述功能更改为不返回而是打印符号,则将 default 分支置于紧急状态仍然是一个好习惯,尽管在此变体中这不是必需的:

If you would change the above function to not return but print the sign, it would still be a good practice to leave the default branch to panic, although it's not a requirement in this variant:

func printSign(a int) {
    switch {
    case a > 0:
        fmt.Println("Positive")
    case a < 0:
        fmt.Println("Negative")
    case a == 0:
        fmt.Println("Zero")
    default:
        panic("unreachable")
    }
}

这篇关于*(* int)(nil)= 0在golang中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 12:10