いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

Goメモ-335 (uber-go/nilaway)(nilの可能性をチェックしてくれる静的解析ツール)(動いた)

関連記事

Goメモ-334 (uber-go/nilaway)(nilの可能性をチェックしてくれる静的解析ツール)(うまく動かなかった・・) - いろいろ備忘録日記

GitHub - devlights/blog-summary: ブログ「いろいろ備忘録日記」のまとめ

概要

前回の状況は関連記事の方を参照いただくとわかると思いますが、私の場合はうまく動いてくれませんでした。

んで、最新版を使ってみたところ、修正されたみたいで動くようになってました。

てことで、試してみました。

試してみる

インストール

$ go install go.uber.org/nilaway/cmd/nilaway@latest
go: downloading go.uber.org/nilaway v0.0.0-20230731204059-143877213b89
go: downloading golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1

 $ ls -l $(go env GOPATH)/bin/nil*
-rwxr-xr-x 1 gitpod gitpod 9678497 Aug  1 09:57 /workspace/go/bin/nilaway

今度はちゃんとインストールされましたね。

nilポが発生するソース1

package main

import (
    "fmt"
    "time"
)

type St struct {
    V int
}

func main() {
    var st *St
    if cond() {
        st = &St{100}
    }
    fmt.Println(st.V)
}

func cond() bool {
    return time.Now().Second()%2 == 0
}

nilawayをかけてみます。

$ nilaway ./...
/workspace/gotmp/main.go:17:14: error: Value read from a variable that was never assigned to (definitely nilable) and is passed to a field access at gotmp/main.go:17:14 (must be nonnil)

おー、ちゃんと検知されましたね。

nilポが発生するソース2

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println(*fn())
}

func fn() *int {
    if time.Now().Second()%2 == 0 {
        v := 100
        return &v
    }

    return nil
}
$ nilaway ./...
/workspace/gotmp/main.go:12:6: error: Annotation on Result 0 of Function fn overconstrained:
Must be NILABLE because it describes the value returned from the function `fn` in position 0 at gotmp/main.go:18:9, and that value is literal nil at gotmp/main.go:18:9, where it is NILABLE
AND
Must be NONNIL because it describes the value returned as result 0 from the method `fn`, and that value is dereferenced at gotmp/main.go:9:15, where it must be NONNIL

こちらもちゃんと検知されました。

参考情報

github.com

Goのおすすめ書籍

Go言語による並行処理

Go言語による並行処理

Amazon


過去の記事については、以下のページからご参照下さい。

サンプルコードは、以下の場所で公開しています。