Convert array to slice in Go

后端 未结 4 632
盖世英雄少女心
盖世英雄少女心 2020-12-07 18:40

This seems like it would be a fairly common thing and abundant examples across the interwebs, but I can\'t seem to find an example of how to convert an [32]byte

相关标签:
4条回答
  • 2020-12-07 18:54

    This will do the trick:

    slice := array[0:len(array)]
    

    Also avoids copying the underlying buffer.

    0 讨论(0)
  • 2020-12-07 19:02

    You can generally slice an array by its bounds with : :

    var a [32]byte 
    slice := a[:]
    

    More generally, for the following array :

    var my_array [LENGTH]TYPE
    

    You can produce the slice of different sizes by writing :

    my_array[START_SLICE:END_SLICE]
    

    Omitting START_SLICE if it equals to the low bound and END_SLICE if equals to the high bound, in your case :

    a[0:32] 
    

    Produces the slice of the underlying array and is equivalent to :

    a[0:]
    a[:32]
    a[:]
    
    0 讨论(0)
  • 2020-12-07 19:04

    This should work:

    func Foo() [32]byte {
        return [32]byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}
    }
    
    func Bar(b []byte) {
        fmt.Println(string(b))
    }
    
    func main() {
        x := Foo()
        Bar(x[:])
    }
    

    And it doesn't create a copy of the underlying buffer

    0 讨论(0)
  • 2020-12-07 19:11
    arr[:]  // arr is an array; arr[:] is the slice of all elements
    
    0 讨论(0)
提交回复
热议问题