| ▲ | quietbritishjim 6 hours ago | |||||||
Hmm interesting. Is there a way to "value initialise" (in C++ speak) an int in Rust to set it to zero? Like `let x: i32 = {};` (without explicitly writing `=0`)? How about a way to do that for a sort of plain struct where there are multiple members you just want to set to their default values? | ||||||||
| ▲ | tialaramex 5 hours ago | parent | next [-] | |||||||
Rust has a Default trait, if your type Goose has a Default then let foo: Goose = Default::default(); Those "primitive" types have a Default, the integers default to zero, as do the floating point types, bool defaults to false, I believe an empty string is the default string (in both the sense that's the default for String, and the default for str, the string slice reference roughly analogous to C++ string_view) Some things don't have a sane default, just as those things wouldn't provide a zero argument constructor in C++. There isn't a default file descriptor, a default network socket, and so on and so those types do not implement Default | ||||||||
| ||||||||
| ▲ | ninkendo 6 hours ago | parent | prev [-] | |||||||
Yep, that's std::mem::zeroed(), which just writes zeroes into the allocated memory regardless of its type... also only available in unsafe code.
prints:
It's unsafe because if Foo contained a String, it would be string with a null pointer inside it and you'd crash trying to read it. If you want "Default" values instead of zeroed (ie. you don't want to run unsafe code), that's what the Default trait is for, and this becomes:
and prints the same thing. | ||||||||