寝ても覚めてもこんぴうた

プログラム書いたり、ネットワーク設計したり、サーバ構築したり、車いじったり、ゲームしたり。そんなひとにわたしはなりたい。 投げ銭は kyash_id : chidakiyo マデ

Goで特定の関数を持つか/実装されているかチェックする方法

f:id:chidakiyo:20191209094946j:plain

いまさらながら、なるほどーと思ったのでメモ。

go1.13のerrorsのUnwrap関数が以下のように実装されている

// Unwrap returns the result of calling the Unwrap method on err, if err's
// type contains an Unwrap method returning error.
// Otherwise, Unwrap returns nil.
func Unwrap(err error) error {
    u, ok := err.(interface {
        Unwrap() error
    })
    if !ok {
        return nil
    }
    return u.Unwrap()
}

error型を型アサーションして、okじゃなかったらUnwrapが実装されていないのでnilを返却する。
okだったらerrorのUnwrap関数を実行して返却する。

なるほどね。