官术网_书友最值得收藏!

Unreachable code

Unreachable code is code that can never be executed and is a logical kind of error. As the Go compiler itself cannot catch such logical errors, you will need to use the go tool vet command to help.

You should not confuse unreachable code with code that never gets executed intentionally, such as the code of a function that is not needed and is therefore not called in a program.

The example code in this section is saved as cannotReach.go and can be divided into two parts.

The first part has the following Go code:

package main 
 
import ( 
   "fmt" 
) 


func x() int {

return -1 fmt.Println("Exiting x()") return -1 } func y() int { return -1 fmt.Println("Exiting y()") return -1 }

The second part is as follows:

func main() { 
   fmt.Println(x()) 
   fmt.Println("Exiting program...") 
} 

As you can see, the unreachable code is in the first part. Both x() and y() functions have unreachable code because their return statements were put at the wrong place. However, we are not done yet because we will have to let the go tool vet tool discover the unreachable code. The process is simple and includes the execution of the following command:

$ go tool vet cannotReach.go
cannotReach.go:9: unreachable code
cannotReach.go:14: unreachable code
 

Additionally, you can see that go tool vet detects unreachable code even if the surrounding function is not going to be executed at all, as happens with y().

主站蜘蛛池模板: 广宁县| 波密县| 吉木萨尔县| 淮滨县| 修文县| 克什克腾旗| 吴旗县| 阿瓦提县| 通州市| 临朐县| 郯城县| 岑溪市| 丹巴县| 大竹县| 凤山县| 泗水县| 沂水县| 潢川县| 磐安县| 化隆| 交城县| 车险| 梧州市| 嘉善县| 定日县| 民权县| 佛学| 枞阳县| 定边县| 西乌珠穆沁旗| 拜城县| 克什克腾旗| 准格尔旗| 麻城市| 永州市| 苍梧县| 巧家县| 攀枝花市| 达孜县| 梧州市| 罗江县|