Rust is awesome language, blazingly fast, low level but of course it can be used in high level targets wery well. Now I will be talk about an interesting operator in Rust: Question Mark Operator.
Everything is about error handling. As you know Rust doesn’t have any try-catch syntax. Instead of there is Result
enum. As you remember your first days of start to programming, you didn’t use try-catch, you just return a zero
, null
, -1
or anything “unvaluable” thing when there is an error. Same thing exist in Rust but this is better way. You can return a Result
enum and this has two fields: Ok
and Error
. As you think if everything is fine, you just return Ok()
or Ok(good_variable)
, but if you something goes wrong you just return Err(any_type_of_error)
. Let’s look at example code:
fn get_file_contents(file_path: &str) -> Result<String, io::Error> { let file = match File::open(file_path) { Ok(f) => f, Err(e) => return Err(e), }; }
This syntax is so common, you can see/make this almost for every Result
type. Rust has a solution for this common thing: question mark operator. We can make same thing with a single question mark:
fn get_file_contents(file_path: &str) -> Result<String, io::Error> { let file = File::open(file_path)?; }
As you can see the code become so pretty, understandable and manageable. This is exactly what “question mark operator” does. Happy coding…
0 yorum