How to filter fields from a mongo document with the official mongo-go-driver

Edit: As the mongo-go driver evolved, it is possible to specify a projection using a simple bson.M like this: options.FindOne().SetProjection(bson.M{“_id”: 0}) Original (old) answer follows. The reason why it doesn’t work for you is because the field fields._id is unexported, and as such, no other package can access it (only the declaring package). You must … Read more

offsetof at compile time

The offsetof() macro is a compile-time construct. There is no standard-compliant way to define it, but every compiler must have some way of doing it. One example would be: #define offsetof( type, member ) ( (size_t) &( ( (type *) 0 )->member ) ) While not being a compile-time construct technically (see comments by user … Read more

Purpose of struct, typedef struct, in C++

Here are the differences between the two declarations/definitions: 1) You cannot use a typedef name to identify a constructor or a destructor struct MyStruct { MyStruct(); ~MyStruct(); }; // ok typedef struct { MyStructTD(); ~MyStructTD(); } MyStructTD; // not ok // now consider typedef struct MyStruct2 { MyStruct2(); } MyStructTD2; // ok MyStructTD2::MyStruct2() { } … Read more

Test for nil values in nested stucts

One elegant way (in my opinion) of handling it is to add getters to structs that are used as pointers. This “technique” is also used by the generated Go code of protobuf, and it allows natural chaining of method calls without having to worry about runtime panic due to nil pointers. In your example the … Read more

Get list of C structure members

Here’s a proof of concept: #include <stdio.h> #include <string.h> #define MEMBER(TYPE,NAME,MORE) TYPE NAME MORE #define TSTRUCT(NAME,MEMBERS) \ typedef struct NAME { \ MEMBERS \ } NAME; \ const char* const NAME##_Members = #MEMBERS; #define PRINT_STRUCT_MEMBERS(NAME) printStructMembers(NAME##_Members) TSTRUCT(S, MEMBER(int,x;, MEMBER(void*,z[2];, MEMBER(char,(*f)(char,char);, MEMBER(char,y;, ))))); void printStructMembers(const char* Members) { int level = 0; int lastLevel = 0; … Read more

C# – Value Type Equals method – why does the compiler use reflection?

The following is the decompiled ValueType.Equals method from mscorlib: public override bool Equals(object obj) { if (obj == null) { return false; } RuntimeType type = (RuntimeType) base.GetType(); RuntimeType type2 = (RuntimeType) obj.GetType(); if (type2 != type) { return false; } object a = this; if (CanCompareBits(this)) { return FastEqualsCheck(a, obj); } FieldInfo[] fields = … Read more