0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Golang】[64]byte や [32]byte を []byte や string に変換する(配列をスライスに変換する)

Last updated at Posted at 2021-06-23

Just Cast Away

固定長の配列(array)を可変長の配列(slice)にしたい。
しかし、スライスにキャスト(型変換)してもエラーが出ます。

つまり、[size]T の配列を、[]T のスライスに変換したいのです。

キャストできない例
foo := [64]byte{}
bar := []byte(foo)
// Output: cannot convert foo (type [64]byte) to type []byte
stringにキャストできない例
foo := [16]byte{}
bar := string(foo)
// Output: cannot convert foo (type [16]byte) to type string

わかっちゃえば何てことないのですが、「"golang" byteの配列を文字列に変換」でググっても、タイトルからは []byte のスライスを string にキャストする方法しか出てこなかったので、自分のググラビリティとして。

TL; DR (今北産業)

  1. [:] を使って slicing する(スライスとして配列を参照させる)

  2. foo[:]foo[0:len(foo)] と同等

  3. オンラインで以下の動作を見る @ Go Playground

    foo := [64]byte{}  // 配列として領域を確保する
    bar := foo[:]      // bar は foo の領域を参照する
    baz := string(bar) // []byte を string にキャスト
    
    // 型を確認する
    fmt.Printf("%T\n", foo)
    fmt.Printf("%T\n", bar)
    fmt.Printf("%T\n", baz)
    
    hoge := [128]string{}
    fuga := hoge[:]
    
    // 型を確認する
    fmt.Printf("%T\n", hoge)
    fmt.Printf("%T\n", fuga)
    
    // Output: 
    // [64]uint8
    // []uint8
    // string
    // [128]string
    // []string
    

参考文献

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?