How to access unexported struct fields

If the struct is addressable, you can use unsafe.Pointer to access the field (read or write) it, like this: rs := reflect.ValueOf(&MyStruct).Elem() rf := rs.Field(n) // rf can’t be read or set. rf = reflect.NewAt(rf.Type(), unsafe.Pointer(rf.UnsafeAddr())).Elem() // Now rf can be read and set. See full example on the playground. This use of unsafe.Pointer is … Read more

Why is it possible to instantiate a struct without the new keyword?

Why are we not forced to instantiate a struct with “new”, like when using a class? When you “new” a reference type, three things happen. First, the memory manager allocates space from long term storage. Second, a reference to that space is passed to the constructor, which initializes the instance. Third, that reference is passed … Read more

Does the ‘readonly’ modifier create a hidden copy of a field?

Does the readonly modifier create a hidden copy of a field? Calling a method or property on a read-only field of a regular struct type (outside the constructor or static constructor) first copies the field, yes. That’s because the compiler doesn’t know whether the property or method access would modify the value you call it … Read more

Forward declaration as struct vs class

struct and class are completely interchangeable as far as forward declarations are concerned. Even for definitions, they only affect the default access specifier of the objects members, everything else is equivalent. You always define “classes” of objects. The only place where struct must be used over class, is when forward declaring opaque data for c … Read more

Rationale behind the container_of macro in linux/list.h

It adds some type checking. With your version, this compiles fine (without warning): struct foo { int bar; }; …. float a; struct foo *var = container_of(&a, foo, bar); With the kernel version, the compiler reports: warning: initialization from incompatible pointer type Good explanation of how the macro works: container_of by Greg Kroah-Hartman.