Free C pointer when collecting GC
It is best done when it is possible to copy the C structure to managed memory.
var ns C.struct_b ns = *A.s A.s = &ns
Obviously this will not work in all cases. C.struct_b might be overly complex or spread with something else in C code. In this case, you need to create a .Free () or .Close () method (whichever makes more sense) and a document to be named by the user of your structure. In Go, a free method must always be call-safe. For example, after starting the free run, make sure to set As = nil so that if the user calls Free twice, the program does not crash.
There is also a way to create finalizers. See another answer I wrote here . However, they may not always start, and if the garbage is generated fast enough, it is very possible that the garbage creation will cause the tempo to be collected. This should be seen as an addition to the Free / Closed method and not a replacement.
source to share