っす。豚野郎です。
今回は例外処理を書いていきます。
Go言語は例外処理構文(try、catch等)がありません。
その中で例外処理を実行していきます。
※ 注意:内容はPHPか何かの言語を書いたことがある方向けなので、
説明を割愛している箇所は多々ありますので、ご了承ください。
go version go1.19.4 darwin/amd64
1. fmt.Errorf()
sample.go
package main
import "strconv"
import "fmt"
// fmt.Errorf()で例外情報作成
// fmt.Errorf()の戻り値の引数はerrorにする。
func Calculation(num int) (string, error) {
if num != 1 {
// Go言語では、エラー情報を2番目に返すことを推奨されている
return "", fmt.Errorf("1ではありません。")
}
num += 1
return "1 + 1 = " + strconv.Itoa(num), nil
}
func main() {
fmt.Println("1を使って足し算を始めます。")
total, e := Calculation(2)
if e != nil {
fmt.Println(e)
} else {
fmt.Println(total)
}
}
$ go run sample.go
1を使って足し算を始めます。
1ではありません。
2. Goto文
sample.go
package main
import "strconv"
import "fmt"
func Calculation(num int) (string, error) {
if num != 1 {
// Doneの処理を呼ぶ
goto Done
}
num += 1
return "1 + 1 = " + strconv.Itoa(num), nil
Done:
return "", fmt.Errorf("1ではありません。")
}
func main() {
fmt.Println("1を使って足し算を始めます。")
total, e := Calculation(2)
if e != nil {
fmt.Println(e)
} else {
fmt.Println(total)
}
}
$ go run sample.go
1を使って足し算を始めます。
1ではありません。
参考
ありがとうございました。