From: Ralf Jung Date: Thu, 17 Nov 2022 13:52:50 +0000 (+0100) Subject: update uninit example so that it still works in current Rust X-Git-Url: https://git.ralfj.de/web.git/commitdiff_plain/b3fe05ec61912f50ffe51ddabf9822bcd3ac5aaa?hp=ed3579d7d6ad285fefc257e67bf65c8a9e963e99 update uninit example so that it still works in current Rust --- diff --git a/personal/_posts/2019-07-14-uninit.md b/personal/_posts/2019-07-14-uninit.md index e5d973b..bbb1468 100644 --- a/personal/_posts/2019-07-14-uninit.md +++ b/personal/_posts/2019-07-14-uninit.md @@ -40,14 +40,16 @@ fn always_returns_true(x: u8) -> bool { } fn main() { - let x: u8 = unsafe { mem::uninitialized() }; + let x: u8 = unsafe { mem::MaybeUninit::uninit().assume_init() }; assert!(always_returns_true(x)); } {% endhighlight %} +**Update (2022-11-17):** Switched to `MaybeUninit` to keep the example working in newer versions of Rust. + `always_returns_true` is a function that, clearly, will return `true` for any possible 8-bit unsigned integer. After all, *every* possible value for `x` will be either less than 120, equal to 120, or bigger than 120. A quick loop [confirms this](https://play.rust-lang.org/?version=stable&mode=release&edition=2018&gist=65b690fa3c1691e11d4d45955358cdbe). -However, if you [run the example](https://play.rust-lang.org/?version=stable&mode=release&edition=2018&gist=812fe3c8655bfedcea37bb18bb70a945), you can see the assertion fail.[^godbolt] +However, if you [run the example](https://play.rust-lang.org/?version=stable&mode=release&edition=2018&gist=c17d299cacd626c572def0c4262aed69), you can see the assertion fail.[^godbolt] [^godbolt]: In case this changes with future Rust versions, [here is the same example on godbolt](https://godbolt.org/z/9G67hP); the `xor eax, eax` indicates that the function returns 0, aka `false`. And [here is a version for C++](https://godbolt.org/z/TWrvcq).