1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Quiz de Go】 NaN を使った map のデータ検索

Posted at

What’s this?

Go の入門者から上級者まで幅広く多くの Gopher が Go を楽しみつくすためのクイズを作りました。
ぜひチャレンジしてみてください!

さっそく問題!

package main
import (
	"fmt"
	"math"
)

func main() {
    m := map[float64]int{}
    m[math.NaN()] = 1
    v, ok := m[math.NaN()]
    fmt.Println(v, ok)
}
  1. 1 true
  2. 1 false
  3. 0 true
  4. 0 false

※環境依存がない前提での出題ですが、何かあればごめんなさい。。。

回答・解説

答えはこちら

正解は 4 の 0 falseです!
正解できましたかね?
簡単だぜ!ってかたはごめんなさい。次こそリベンジします。

解説はこんな感じです。

package main
import (
	"fmt"
	"math"
)
func main() {
	m := map[float64]int{}
    // float64型はGoで「比較可能(comparable)」なのでmapのキーに使うことができる

    m[math.NaN()] = 1
    // NaNもfloat64の値なので、技術的にはmapのキーとして登録できる

    v, ok := m[math.NaN()]
    // ここで再びmath.NaN()をキーに==の検索を実施
	// しかしGoの==演算子はIEEE-754(浮動小数点の規格)に従っており、「NaN == NaN は常に false」
	// そのため、map検索時に Nan == NaNになり「同じキー」と判定できない
	// 結果として、さきほど追加した要素を見つけられず、ゼロ値とfalseが返る

	fmt.Println(v, ok) 	// 出力: 0 false
}

References

さいごに

どうでしたか?
Gopher のみなさん、楽しんでもらえましたかね?
今回余裕の正解だった上級者の方はごめんなさい。次こそリベンジします!
今後も Go の勉強になるようなクイズを作りますので、次回のチャレンジもお待ちしております!

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?