Avatar ·

What is null/nil in Rust and how to work with it?

Hello everyone! I started learning Rust after C++/Java, and I can't figure out the concept of null/nil. In other languages, I'm used to variables being able to be null (or nil), which often led to NullPointerException. As far as I understand, this shouldn't happen in Rust, but then how do you work with the absence of a value?\n\nI've already read about Option and understand that it's analogous to Optional in Java or Maybe in Haskell. But in practice, I'm having difficulties. Here's an example of code I wrote:\n\n```rust\nfn find_user(id: i32) -> Option {\n if id == 1 {\n Some(String::from("Alice"))\n } else {\n None\n }\n}\n\nfn main() {\n let user = find_user(2);\n // How to properly handle this case?\n // I tried this:\n // let name = user.unwrap(); // panics