DEV Community

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

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.