1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Golangで未使用の変数エラーを消す方法

Posted at

stringconv.Atoiなどのerrを二つ目の返り値として返してくれる関数を利用する際、errに代入した後使用しないと実行時にエラーが発生します。

func main() {
  var stdin = bufio.NewScanner(os.Stdin)
  stdin.Scan()
  var n, err = strconv.Atoi(stdin.Text())
  fmt.Println(n)
}
$ go run hoge.go
# command-line-arguments
./x_cubic.go:13:7: assignment mismatch: 1 variable but strconv.Atoi returns 2 values

しかしだからといって二つの返り値を変数に格納しないと、割り当てが間違っているという別のエラーが返却されることになります。

$ go run x_cubic.go
# command-line-arguments
./x_cubic.go:13:7: assignment mismatch: 1 variable but strconv.Atoi returns 2 values

そのため必ず返り値を変数に代入する必要があるのですが、未使用エラーを発生させない必要があります。

このような状況の場合、_(アンダースコア)を利用するとエラーが発生しなくなります。


func main() {
  var stdin = bufio.NewScanner(os.Stdin)
  stdin.Scan()
  var n, _ = strconv.Atoi(stdin.Text())
  fmt.Println(n)
}

これはGo公式ではBlank identifierという名称になっているようです。

参考

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?