Go goto Statement
Go goto statement
goto Statement
The goto statement jumps to a specified label.
Go does not support exception-handling syntax such as try, catch, and raise. To implement similar control flow, write code as follows.
package main
import (
"fmt"
"errors"
)
func main() {
funcA()
}
func funcA() (string, error) {
var err error
filename := ""
data := ""
filename, err = GetFileName()
if err != nil {
fmt.Println(err)
goto Done
}
data, err = ReadFile(filename)
if err != nil {
fmt.Println(err)
goto Done
}
fmt.Println(data)
Done:
return data, err
}
func GetFileName() (string, error) {
return "sample.txt", nil
}
func ReadFile (filename string) (string, error) {
return "Hello world!", errors.New("Can't read file")
}
Output when the sample.txt file does not exist:
Can't read file