These are chat archives for rust-lang/rust

12th
Nov 2015
Dmitry Golubets
@DGolubets
Nov 12 2015 21:59
Hi guys
I'm very new to Rust
I'm trying to convert a simple C util to it
It invokes many Windows API
You know, you often have to create some kind of struct and pass it's address to API function
like let msg = MSG { hwnd: 0, message: 0, wParam: 0, lParam: 0, time: 0, pt: 0 };
I wonder if there is a simplier way of doing this
Can I just allocate a memory for that struct and zero it?
panicbit
@panicbit
Nov 12 2015 22:04
In theory yes, but since that's unsafe a "constructor" would be recommended
(a 'static' function that creates the struct)
Another option is to derive the "Default" Trait, which will give you a default value for that struct
Dmitry Golubets
@DGolubets
Nov 12 2015 22:06
I'm using an existing winapi crate to save me time defining external apis
it has no Defaults defined
and sine my app is very small, defining my own feels like overkill
panicbit
@panicbit
Nov 12 2015 22:08
In that case you should probably go for a function that constructs what you want
Dmitry Golubets
@DGolubets
Nov 12 2015 22:12
that's still a lot of writing.. feels unnatural
I mean, I pass an address to initialize it
but Rust forces me to initialize it before initializing it..
panicbit
@panicbit
Nov 12 2015 22:13
oh I see
You could make use of std::mem::zeroed http://doc.rust-lang.org/nightly/std/mem/fn.zeroed.html
Make sure to read the documentation carefully
It should be safe to use if the struct only contains primitive types
But if you have anything in there that's on the heap, you'll probably get a double free when the struct isn't initialized properly before leaving scope
Dmitry Golubets
@DGolubets
Nov 12 2015 22:16
wow, thanks! that's what I needed
panicbit
@panicbit
Nov 12 2015 22:17
:)
Dmitry Golubets
@DGolubets
Nov 12 2015 22:17
I think it should be ok, cos this struct is only for FFI and managed only by external api
panicbit
@panicbit
Nov 12 2015 22:17
eyup
and there's nothing that implements Drop
Yeah, should definitely be fine to use for this struct
Dmitry Golubets
@DGolubets
Nov 12 2015 22:19
cool, thanks a lot )