go - os.Exit 后不应该无法访问代码

标签 go

去 1.12 窗口

在 os.Exit 之后而不是之前放错了 fmt.Println,
这不应该导致编译器失败或至少警告吗?

package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println("Hello, playground")
    os.Exit(0)
    fmt.Println("Good By, playground")
}

最佳答案

os.Exit() 就像任何其他函数一样,编译器不应该知道它会终止应用程序,因此后面的其余代码是无法访问的。 os.Exit()只是一个例子,还有更多,例如 log.Fatal() (调用 os.Exit() )。更不用说您还可以创建一个调用其中之一的函数,编译器应该多远才能检测到所有或大部分?
更进一步,Go 编译器不会检测或标记“真正”无法访问的代码。使用 return 时的以下变化声明甚至对编译器来说是显而易见的:

func main() {
    fmt.Println("Hello, playground")
    return
    fmt.Println("Good By, playground")
}
然而它编译和运行得很好,并且输出(在 Go Playground 上试试):
Hello, playground
所以编译器不会检测到无法访问的代码,而是go vet确实,它也由 Go Playground 运行,因此您可以看到应用程序的输出前缀为:
./prog.go:10:2: unreachable code
Go vet exited.
之前已经提出过,请参阅 cmd/gc: report unreachable code #9501 .罗伯特·格里斯默的回应是:

Generally, Go's philosophy is not to protect the programmer at all costs from his/her mistakes. It's deliberate to not raise an error for unreachable code. It's also not a very common kind of mistake. Besides, it's often useful to introduce early returns for debugging which may cause plenty of unreachable code. It's not clear the benefits outweigh the costs and disadvantages.

Unused variables can lead to subtle find bugs in conjunction with Go's re-declaration mechanism in short variable declarations - hence the error message for unused variables. This is a mechanism that evolved from experience and is a pragmatic solution for a concrete problem.

Unused imports are reported because it helps keeping dependencies under control - an important tool in large-scale systems design and as a side-effect it also keeps compile times fast. Again a very deliberate design decision.

Finally, making dead code an error would be a significant language change which is out of the question at this point.

Use go vet.

关于go - os.Exit 后不应该无法访问代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59456618/

相关文章:

go - 在 Golang 中测试命名约定

algorithm - 为什么 "Split"不是 Go 中 "string"类型的成员函数?

go - 使用 JulienSchmidt httprouter 服务 favicon.ico

json - 如何将 JSON 解码为由不同代码段提供的 Go 结构?

go - 缓冲区问题不能在 http.NewRequest golang 的参数中使用 <type> 作为 io.Reader 类型

go - 从函数返回未导出的类型

for-loop - 由于我的 if 语句,我的 for 循环停止处理

json - 无法将字符串解码到 Go 结构字段中

go - Go 例程中的 Websockets : error previous message not read to completion

go - filepath.Base 在 golang 中做什么