55
31

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.

2つのsliceがすべて同じ要素をもっているかどうかを比較するショートカット

Last updated at Posted at 2013-11-29

Goでは同じサイズの配列同士の比較には==演算子が使えるが、サイズが違う配列やslice同士の比較には==が使えない。

手っ取り早く比較したいときはreflect.DeepEqualをつかうとタイプ数が少なくて便利。

package main

import (
        "fmt"
        "reflect"
)

func main() {
        a := []byte{1, 2, 3}
        b := []byte{1, 2, 3, 4}
        c := [3]byte{1, 2, 3}

        // これはコンパイルエラー
        // fmt.Println(a == b)
        // fmt.Println(a == c)

        // reflect.DeepEqual をつかうと何でも比較できる
        fmt.Println(reflect.DeepEqual(a, b))      // => false
        fmt.Println(reflect.DeepEqual(a, b[0:3])) // => true
        fmt.Println(reflect.DeepEqual(a, c))      // => false
        fmt.Println(reflect.DeepEqual(a, c[:]))   // => true
}

gomegaのmatcherが使ってたのを見て知った。

55
31
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
55
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?