3 ms·
But an idiom from C which might inspire some unsafe rust is to memset a struct to zero after declaration in order to guarantee that all fields are initialized b
by wyldfire 5y ago
But an idiom from C which might inspire some unsafe rust is to memset a struct to zero after declaration in order to guarantee that all fields are initialized before anything would access them.
- MaxBarraclough 5y agoIf I understand correctly, reading [0], in C99 (or later) you can do that with struct MyStruct foo = {}; This has the effect of initializing all members to zero (or, more precisely, the value which is the same as for objects that have static storage duration [0]). [0] https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html See also Stop Memsetting Structures: https://news.ycombinator.com/item?id=19766930 https://news.ycombinator.com/item?id=19766930
- Arch-TK 5y agoYou need to put something in those braces. An empty initializer list is not allowed by C99 or C11. That being said, you only need to put ONE thing in there, the rest will then be initialized as you described.
- MaxBarraclough 5y agoThanks, StackOverflow confirms you're correct. [0] That's what I get for using GCC as an approximation of the C standard. (By default, GCC permits empty initializer lists.) [0] https://stackoverflow.com/a/17589839/ https://stackoverflow.com/a/17589839/
- Lvl999Noob 5y agoIs initializing a NonZero field to 0 really initializing it?
- staticassertion 5y agoSort of. It's definitely better than not initializing it.
- dathinab 5y agono not at all IMHO requiring all types in C to have a valid "all zero" variant so that this pattern can be used isn't grate either, somewhat of an anti-pattern even. But an anti-pattern needed for ergonomic C. The post is a good example for trying to program "like in a different language" just because some tools somewhat allow it. Like in this case "programming rust like it's C". And if you do rust FFI and have a lot of C experience it is tempting.