Thank you! Yes, the last 2 examples are much clearer to my eyes. And it's on the tutorial too:
File::open("hello.txt")?.read_to_string(&mut s)?;
I should pay more attention :)
But I also deduce 2 things:
- That unwrap should not be used in the kernel, correct?
- That I should be very careful about the external libraries I use and look for the presence of panic! and/or unwrap, or use https://docs.rs/no-panic/0.1.13/no_panic/ as jononor commented here below. But I guess this might rule-out some useful libraries from a project.
> That unwrap should not be used in the kernel, correct?
More or less. There could be situations where you know the error is impossible and it is reasonable to unwrap. But it's a good rule of thumb.
> That I should be very careful about the external libraries I use and look for the presence of panic! and/or unwrap, or use https://docs.rs/no-panic/0.1.13/no_panic/ as jononor commented here below. But I guess this might rule-out some useful libraries from a project.
Absolutely! Use of unsafe is another potential watch-point.
> - That unwrap should not be used in the kernel, correct?
Yes.
I guess the exception is if it will only panic on a kernel bug and you're ok with that (that's what the bug macro is for, no)? E.g. if I have `let x = Some(2); let y = x.unwrap();`. The second statement panics if x is None, but that would only happen in the event of a bug, so you might be ok with it.
This does happen sometimes in real code, `if some_list.len() > 2 { let x = some_list.pop().unwrap() }` will never panic, because pop() only returns None (think null) if the list is empty, but we just checked it has at least two elements. I'm not sure what the kernels stance on this sort of code will be.
> - That I should be very careful about the external libraries I use and look for the presence of panic! and/or unwrap,
In the context of the kernel, I imagine you just don't use external libraries at all. In a more general context, yes, you need to understand when any libraries you use might panic. The general convention that is honestly not very well followed is to document panics that result from usage errors, and to allow for panics caused by library bugs.
But I also deduce 2 things:
- That unwrap should not be used in the kernel, correct?
- That I should be very careful about the external libraries I use and look for the presence of panic! and/or unwrap, or use https://docs.rs/no-panic/0.1.13/no_panic/ as jononor commented here below. But I guess this might rule-out some useful libraries from a project.