How to convert a slice into a fixed-size array?

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 leads to:

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

How to convert a slice to a fixed-size array?

+16
arrays slice go
source share
1 answer

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) 

since the copy will always copy at least len(src) and len(dst) bytes.

+44
source share

All Articles