DEV Community

Discussion on: A story of data hiding and why you shouldn't

yujiri8 profile image
Ryan Westlund Author

So you're telling me there isn't an actual way to convert directly from a reflect.Value that represents a slice to an actual slice type, I would've had to use Len and Index or Slice to rebuild the slice?

Thread Thread
yoursunny profile image
Junxiao Shi

play.golang.org/p/ADAMCB_GuTE

package main

import (
    "fmt"
    "reflect"
    "unsafe"
)

type X struct {
    y []string
}

func main() {
    x := new(X)
    x.y = []string{"yyyy"}

    vx := reflect.ValueOf(x)
    vy := vx.Elem().FieldByName("y")

    var y []string
    *(*reflect.SliceHeader)(unsafe.Pointer(&y)) = *(*reflect.SliceHeader)(unsafe.Pointer(vy.UnsafeAddr()))

    fmt.Println(y)
}
Enter fullscreen mode Exit fullscreen mode

You can use SliceHeader. However, this requires the unsafe package.

Thread Thread
yujiri8 profile image
Ryan Westlund Author

That is quite some black magic.