Comment by jeroenhd

5 hours ago

Lifetime tracking and ownership are very difficult. That's why languages like C and C++ don't do it. It's also why those languages needs tons of extra validation steps and analysis tools to prevent bugs.

Arc is nothing more than reference counting. C++ can do that too, and I'm sure there are C libraries for it. That's not an admission of anything, it's actually solving the problem rather than ignoring it and hoping it doesn't crash your program in fun and unexpected ways.

Using Arc also comes with a performance hit because validation needs to be done at runtime. You can go back to the faster C/C++ style data exchange by wrapping your code in unsafe {} blocks, though, but the risks of memory corruption, concurrent access, and using deallocated memory are on you if you do it, and those are generally the whole reason people pick Rust over C++ in the first place.

Looking at the code, it consists of long chains of get().unwrap().to_mut().unwrap().get() noise. Looks like coping with library design than ownership tacking. Also why Result<Option<T>>? Isn't Result already Option by itself? I guess that's why you need get().unwrap().to_mut() to get a value from Result<Option<T>> from an average function call?

  • >> Also why Result<Option<T>>? Isn't Result already Option by itself?

    No. I've written code that returns Result<Option<T>>. It was a wrapper for a server's query web API.

    The Result part determines whether the request succeeded and the response is valid.

    The Option part is because the parameter being queried might not exist. For example, if I ask the API for the current state of the user session with a given Session ID, but that Session ID does not exist, then the Rust wrapper could return OK(None) meaning that the request succeeded, but that no such session was found.

  • If I ask my repository (backed by an sql db) to get a user, there might be 3 different scenarios I'm interested in:

    - Technical problem (like connection problems) means I don't know what's in the db

    - No technical problem, but no user entry

    - No technical problem, and a user entry

    You need the Result for the technical problems, and the Option for whether there's a user entry or not.