🐡
golang やってみた(3)
Return and handle an error
前回の続きで、エラーのときの処理を書きます。
挨拶する相手がわからない(名前が空)場合は、エラーを返すようにします。
greetings.go
package greetings
import (
"errors"
"fmt"
)
// Hello returns a greeting for the named person.
func Hello(name string) (string, error) {
// If no name was given, return an error with a message.
if name == "" {
return "", errors.New("empty name")
}
// If a name was received, return a value that embeds the name
// in a greeting message.
message := fmt.Srintf("Hi, %v. Welcome!", name)
return message, nil
}
次にhello.goを次のように変更します。
package main
import (
"fmt"
"log"
"example.com/greetings"
)
func main() {
// Set properties of the predefined Logger, including
// the log entry prefix and a flag to disable printing
// the time, source file, and line number.
log.SetPrefix("greetings: ")
log.SetFlags(0)
// Request a greeting message.
message, err := greetings.Hello("")
// If an error was returned, print it to the console and
// exit the program.
if err != nil {
log.Fatal(err)
}
// If no error was returned, print the returned message
// to the console.
fmt.Println(message)
}
早速実行すると、、
go run .
結果、下記のようになります。
greetings: empty name
exit status 1
Discussion