DEV Community

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

yoursunny profile image
Junxiao Shi

package main

import (

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()))

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.