Better way to declare uninitialized variables

后端 未结 1 762
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-25 09:17

Some libc functions, e.g. sigemptyset(set: *mut sigset_t) take a pointer to a variable, treat it as uninitialized and initialize it.

I end up with this code:

<         


        
相关标签:
1条回答
  • 2021-01-25 10:01

    Luckily, tuples are normal types, too. So how about:

    let (mut newmask, mut oldmask, mut pendmask) = std::mem::uninitialized();
    

    However, it won't get much nicer than this. Your best bet is to combine all your variables into a bigger type (like a tuple or a struct) and un-initialize that.

    But it's fine that unsafe things are verbose and annoying to write. Uninitialized variables are really quite dangerous, especially when dealing with Drop types. I am sure you are already aware, but I still want to make sure everyone reads the documentation of uninitialized() to understand all possible pitfalls.

    0 讨论(0)
提交回复
热议问题