English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang 基礎トレーニング

Golang 控制文

Golang 関数 & メソッド

Golang 構造体

Golang スライス & 配列

Golang 文字列(String)

Golang ポインタ

Golang インターフェース

Golang 并行

Golang エラ(Error)

Golang その他の雑項

Go スライスの比較

Go言語では、スライスは配列よりも強力で、柔軟で便利で、軽量なデータ構造です。スライスは可変長のシーケンスで、同じタイプの要素を格納するために使用され、同一切片中に異なるタイプの要素を格納することは許可されていません。Goのスライスでは、Compare()関数は2つのバイトスライスを相互に比較します。比較。この関数は整数値を返し、これらのスライスが一致するかどうかを示します。これらの値は:

  • もし結果が0ならば、slice_1 == slice_2。

  • もし結果が-1、则slice_1 <slice_2。

  • もし結果が+1、则slice_1> slice_2。

この関数はbytesパッケージで定義されていますので、Compare関数にアクセスするには、プログラムでbytesパッケージをインポートする必要があります。

文法:

func Compare(slice_1, slice_2 []byte) int

この概念について例を用いて説明しましょう:

//2つのバイトスライスを比較
package main
import (
    "bytes"
    "fmt"
)
func main() {
    //短縮宣言を使用してスライスを作成および初期化
    slice_1 := []byte{'G', 'E', 'E', 'K', 'S'}
    slice_2 := []byte{'G', 'E', 'e', 'K', 'S'}
    //スライスを比較
    //使用Compare関数
    res := bytes.Compare(slice_1, slice_2)
    if res == 0 {
        fmt.Println("!..スライスが一致する..!")
    } else {
        fmt.Println("!..スライスが異なる..!")
    }
}

出力:

!..スライスが異なる..!

2つのバイトのスライスを比較する例:

package main
import (
    "bytes"
    "fmt"
)
func main() {
    slice_1 := []byte{'A', 'N', 'M', 'O', 'P', 'Q'}
    slice_2 := []byte{'a', 'g', 't', 'e', 'q', 'm'}
    slice_3 := []byte{'A', 'N', 'M', 'O', 'P', 'Q'}
    slice_4 := []byte{'A', 'n', 'M', 'o', 'p', 'Q'}
    //スライスを表示
    fmt.Println("スライス" 1: ", slice_1)
    fmt.Println("スライス" 2: ", slice_2)
    fmt.Println("スライス" 3: ", slice_3)
    fmt.Println("スライス" 4: ", slice_4)
    //スライスを比較, 使用Compare
    res1 := bytes.Compare(slice_1, slice_2)
    res2 := bytes.Compare(slice_1, slice_3)
    res3 := bytes.Compare(slice_1, slice_4)
    res4 := bytes.Compare(slice_2, slice_3)
    res5 := bytes.Compare(slice_2, slice_4)
    res6 := bytes.Compare(slice_2, slice_1)
    res7 := bytes.Compare(slice_3, slice_1)
    res8 := bytes.Compare(slice_3, slice_2)
    res9 := bytes.Compare(slice_3, slice_4)
    res10 := bytes.Compare(slice_4, slice_1)
    res11 := bytes.Compare(slice_4, slice_2)
    res12 := bytes.Compare(slice_4, slice_3)
    res13 := bytes.Compare(slice_4, slice_4)
    fmt.Println("\n結果" 1:", res1)
    fmt.Println("結果" 2:", res2)
    fmt.Println("結果" 3:", res3)
    fmt.Println("結果" 4:", res4)
    fmt.Println("結果" 5:", res5)
    fmt.Println("結果" 6:", res6)
    fmt.Println("結果" 7:", res7)
    fmt.Println("結果" 8:", res8)
    fmt.Println("結果" 9:", res9)
    fmt.Println("結果" 10:", res10)
    fmt.Println("結果" 11:", res11)
    fmt.Println("結果" 12:", res12)
    fmt.Println("結果" 13:", res13)
}

出力:

スライス 1:  [65 78 77 79 80 81]
スライス 2:  [97 103 116 101 113 109]
スライス 3:  [65 78 77 79 80 81]
スライス 4:  [65 110 77 111 112 81]
結果 1: -1
結果 2: 0
結果 3: -1
結果 4: 1
結果 5: 1
結果 6: 1
結果 7: 0
結果 8: -1
結果 9: -1
結果 10: 1
結果 11: -1
結果 12: 1
結果 13: 0