Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert slice to fixed size array? [duplicate]

Tags:

arrays

slice

go

I want to convert a fixed size array from a slice:

func gen(bricks []Brick) {
    if len(bricks) == 16 {
        if check(Sculpture{bricks}) {
            var b [16]Brick = bricks[0:16];
        }
     }
}

But this results in:

 cannot use bricks[0:16] (type []Brick) as type [16]Brick in assignment

How to convert a slice into a fixed size array?

like image 455
thi gg Avatar asked May 17 '15 10:05

thi gg


2 Answers

Edit: as of Go 1.17+, you may be able to use new support for slice-to-array conversions, https://tip.golang.org/ref/spec#Conversions_from_slice_to_array_pointer:

s := make([]byte, 2, 4)
s0 := (*[0]byte)(s)      // s0 != nil
s1 := (*[1]byte)(s[1:])  // &s1[0] == &s[1]
s2 := (*[2]byte)(s)      // &s2[0] == &s[0]
s4 := (*[4]byte)(s)      // panics: len([4]byte) > len(s)

Previous answer for Go 1.16 and below:

You need to use copy:

slice := []byte("abcdefgh")

var arr [4]byte

copy(arr[:], slice[:4])

fmt.Println(arr)

As Aedolon notes you can also just use

copy(arr[:], slice)

as copy will always only copy the minimum of len(src) and len(dst) bytes.

like image 88
Stephan Dollberg Avatar answered Nov 12 '22 16:11

Stephan Dollberg


I found a way to solve the problem without allocating any more space - to define a new struct with the same construction as slice and receive the unsafe.Pointer.

type MySlice struct {
    Array unsafe.Pointer
    cap   int
    len   int
}
func main(){
    a := []byte{1, 2, 3, 4}
    fmt.Printf("a before %v, %p\n", a, &a)
    b := (*MySlice)(unsafe.Pointer(&a))
    c := (*[4]byte)(b.Array)
    fmt.Printf("c before %v, %T, %p\n", *c, *c, c)
    a[1] = 5
    fmt.Printf("c after %v, %p\n", *c, c)
    fmt.Printf("a after %v, %p\n", a, &a)
}

the result shows as follows: result

like image 21
Yiheng Avatar answered Nov 12 '22 16:11

Yiheng