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

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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1