Access unexported struct fields in Go
Saturday 15 April 2023
  • In Delve there is a struct called Debugger
  • it has an unexported field called called targetMutex
  • I want to access the TryLock method of this mutex in my package, but as it’s not exported I can’t do that

The following code is a workaround. it accesses the field and casts it to a pointer of sync.Mutex

1func TryLockTarget(d *debugger.Debugger) bool {
2	field := reflect.ValueOf(d).Elem().FieldByName("targetMutex")
3	mtx := reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Interface()
4	return mtx.(*sync.Mutex).TryLock()
5}

The it’s part of my Delve GUI. you can find the original snippet here: https://github.com/emad-elsaid…

#go

See Also