Unreachable code after return processing( go vet command)

“go vet” command will give you unreachable code
I want to process to the end, but I get unreachable code.
How to return in for …

//main.go
package main

import "fmt"

func main() {
  var inputs string
  fmt.Println("Please enter the characters,Valid characters:【go】")
  fmt.Scan(&inputs)
  fmt.Println(returnfunc(inputs))
}


func returnfunc(input string)(a string){
  switch input {
    case "go":
    message := "golang will start!"+"Go is a tool for managing Go source code..."
    return message
    default:
    messageerror := "ERROR: " + input + " is an invalid error  Target method: Take a close look at the valid code,【 go 】 is valid"
    return messageerror
  }
  for {
    folang := input
    fmt.Println("start for")
    return folang
  }
  fmt.Println("Ended.")
  return
}

Your for is running a single time and then returns from the function.

That’s why 1. The code behind it is unreachable and 2. the wrapping for unnecessary.

Also, both of your switch clauses do return already, so even the for is unreachable.

Is it correct for me that if I return to the function, the subsequent processing cannot be reached?

return means “exit the current function and pass the given return value to the calling function”, so of course code that follows a return and is in the same branch, can never be reached.

1 Like

Such code does not compile. Consider this:

package main

import (
	"fmt"
)

func foo() {
	fmt.Println("before")
	return
	fmt.Println("after") // <-- unreachable code
}

func main() {
	foo()
}

The Go compiler will tell you:

./prog.go:10:2: unreachable code
1 Like

I’m glad that I can understand the reason why the processing after return is not possible. Thank you very much ^ ^

Your example code does compile because it is legal code.

The Go Programming Language Specification

The code is reported by vet as containing a suspicious construct: unreachable code.

Command vet

Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string. Vet uses heuristics that do not guarantee all reports are genuine problems, but it can find errors not caught by the compilers.


$ cat reach.go
package main

import (
    "fmt"
)

func foo() {
    fmt.Println("before")
    return
    fmt.Println("after") // <-- unreachable code
}

func main() {
    foo()
}

.

$ go version
go version devel +e82c9bd8 Wed Sep 16 08:49:14 2020 +0000 linux/amd64
$ go run reach.go
before
$ go vet reach.go
# command-line-arguments
./reach.go:10:2: unreachable code
$ 

https://play.golang.org/p/XnQYIOcg8hp

./prog.go:10:2: unreachable code
Go vet exited.

before
1 Like

You are correct. So let’s just say that warnings should not be ignored and can be helpful.