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()) ...

Get Go Systems Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.