To create a slice from an array using reflection in Golang, you need to follow these steps:
reflect
package:import "reflect"
array := [5]int{1, 2, 3, 4, 5}
arrayValue := reflect.ValueOf(array)
sliceValue := arrayValue.Slice(0, arrayValue.Len())
[]int
type:slice := sliceValue.Interface().([]int)
Here's the complete code example:
package main
import (
"fmt"
"reflect"
)
func main() {
array := [5]int{1, 2, 3, 4, 5}
arrayValue := reflect.ValueOf(array)
sliceValue := arrayValue.Slice(0, arrayValue.Len())
slice := sliceValue.Interface().([]int)
fmt.Println(slice)
}
Running this code will output the slice created from the array: [1 2 3 4 5]
.