3 ms·
Rust memory management is just RAII, and there are no exceptions, just nice Result types and syntax that makes returning them and handling error cases simple an
by arcticbull 8y ago
Rust memory management is just RAII, and there are no exceptions, just nice Result types and syntax that makes returning them and handling error cases simple and pleasant.
If you want to handle closing a socket, it’s as easy as implementing the Drop trait on your type. Without an unsafe block there’s no way your destructor won’t be called.
struct Socket(u16);
impl Drop for Socket {...}
To answer your question there’s no special casing around memory vs non-memory resources. Your socket is backed by a kernel ID which must exist in memory, of course, so by adding a Drop implementation you can then define the special treatment yourself. If threading considerations exist you can explore the Sync and Send marker traits too.
It’s largely a much simpler language than C++, you just have to learn how to write it. A lot of the friction/confusion IMO is that it looks so similar to languages you use at first glance you just start writing the code you used to in a Rust-y way, instead of Rust, then are frustrated as to why it won’t build.
In some ways it’d be clearer if it looked “foreign” like prolog — it’d be a lot less popular though haha.
- 0815test 8y ago> ...Without an unsafe block there’s no way your destructor won’t be called. Unfortunately, this is not correct. Resource "leaks", involving failure to drop a resource which is no longer in use, are possible in Rust, and the borrow-checker won't protect against them. They're most likely very rare in idiomatic Rust (the case I know about has to do with RC-cycles) but they're possible.
- CDSlice 8y agoYou can also use the (safe!) function std::mem::forget > forget is not marked as unsafe, because Rust's safety guarantees do not include a guarantee that destructors will always run. For example, a program can create a reference cycle using Rc, or call process::exit to exit without running destructors. Thus, allowing mem::forget from safe code does not fundamentally change Rust's safety guarantees. ... Because forgetting a value is allowed, any unsafe code you write must allow for this possibility. You cannot return a value and expect that the caller will necessarily run the value's destructor. https://doc.rust-lang.org/std/mem/fn.forget.html https://doc.rust-lang.org/std/mem/fn.forget.html