Skip to contentSkip to conversation

rust: error: Extend the Result documentation

PATCH Applied Dirk Behme 4 participants 7 messages Jan 22, 2025 – Mar 16, 2025 Rust

lore
Share & tools
lore

Dirk Behme

author
#0 lore raw

PATCH v4 1/1 rust: error: Extend the Result documentation

Extend the Result documentation by some guidelines and examples how to handle Result error cases gracefully. And how to not handle them.

While at it fix one missing Result link in the existing documentation.

---

Changes in v4:
* Drop the expect() example and put the slightly rephrased unwrap()/expect() description below the ?-operator example (Alice & Miguel)

Changes in v3:
* Slight rephrase regarding panic() vs BUG(), whitespace and newline fixes, use srctree/ syntax, add Rust reference link for Result(), evaluate the result of the examples etc. (Miguel)

Changes in v2:
* Improve the linkage (Daniel & Alice)
* Reformat the examples, add if let, drop "automatically", call the example(), improve the formatting, etc (Miguel)

 rust/kernel/error.rs | 113 ++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 112 insertions(+), 1 deletion(-)
rust/kernel/error.rs +112 -1
index 0b01975c2286c..b4e59feb17a7f 100644
@@ -254,8 +254,119 @@ fn from(e: core::convert::Infallible) -> Error {
 /// [`Error`] as its error type.
 ///
 /// Note that even if a function does not return anything when it succeeds,
-/// it should still be modeled as returning a `Result` rather than
+/// it should still be modeled as returning a [`Result`] rather than
 /// just an [`Error`].
+///
+/// Calling a function that returns [`Result`] needs the caller to handle
+/// the returned [`Result`].
+///
+/// This can be done "manually" by using [`match`]. Using [`match`] to decode
+/// the [`Result`] is similar to C where all the return value decoding and the
+/// error handling is done explicitly by writing handling code for each
+/// error to cover. Using [`match`] the error and success handling can be
+/// implemented in all detail as required. For example (inspired by
+/// [samples/rust/rust_minimal.rs]):
+///
+/// ```
+/// fn example() -> Result {
+///     let mut numbers = KVec::new();
+///
+///     match numbers.push(72, GFP_KERNEL) {
+///         Err(e) => {
+///             pr_err!("Error pushing 72: {e:?}");
+///             return Err(e.into());
+///         }
+///         // Do nothing, continue.
+///         Ok(()) => (),
+///     }
+///
+///     match numbers.push(108, GFP_KERNEL) {
+///         Err(e) => {
+///             pr_err!("Error pushing 108: {e:?}");
+///             return Err(e.into());
+///         }
+///         // Do nothing, continue.
+///         Ok(()) => (),
+///     }
+///
+///     match numbers.push(200, GFP_KERNEL) {
+///         Err(e) => {
+///             pr_err!("Error pushing 200: {e:?}");
+///             return Err(e.into());
+///         }
+///         // Do nothing, continue.
+///         Ok(()) => (),
+///     }
+///
+///     Ok(())
+/// }
+/// # example()?;
+/// # Ok::<(), Error>(())
+/// ```
+///
+/// An alternative to be more concise is the [`if let`] syntax:
+///
+/// ```
+/// fn example() -> Result {
+///     let mut numbers = KVec::new();
+///
+///     if let Err(e) = numbers.push(72, GFP_KERNEL) {
+///         pr_err!("Error pushing 72: {e:?}");
+///         return Err(e.into());
+///     }
+///
+///     if let Err(e) = numbers.push(108, GFP_KERNEL) {
+///         pr_err!("Error pushing 108: {e:?}");
+///         return Err(e.into());
+///     }
+///
+///     if let Err(e) = numbers.push(200, GFP_KERNEL) {
+///         pr_err!("Error pushing 200: {e:?}");
+///         return Err(e.into());
+///     }
+///
+///     Ok(())
+/// }
+/// # example()?;
+/// # Ok::<(), Error>(())
+/// ```
+///
+/// Instead of these verbose [`match`]/[`if let`] the [`?`]-operator can
+/// be used to handle the [`Result`]. Using the [`?`]-operator is often
+/// the best choice to handle [`Result`] in a non-verbose way as done in
+/// [samples/rust/rust_minimal.rs]:
+///
+/// ```
+/// fn example() -> Result {
+///     let mut numbers = KVec::new();
+///     numbers.push(72, GFP_KERNEL)?;
+///     numbers.push(108, GFP_KERNEL)?;
+///     numbers.push(200, GFP_KERNEL)?;
+///     Ok(())
+/// }
+/// # example()?;
+/// # Ok::<(), Error>(())
+/// ```
+/// Another possibility is to call [`unwrap()`](Result::unwrap) or
+/// [`expect()`](Result::expect). However, use of these functions is
+/// *heavily discouraged* in the kernel because they trigger a Rust
+/// [`panic`] if an error happens, which may destabilize the system or
+/// entirely break it as a result -- just like the C [`BUG()`] macro.
+/// Please see the documentation for the C macro [`BUG()`] for guidance
+/// on when to use these functions. Alternatively, depending on the use
+/// case, using [`unwrap_or()`](Result::unwrap_or),
+/// [`unwrap_or_else()`](Result::unwrap_or_else),
+/// [`unwrap_or_default()`](Result::unwrap_or_default) or
+/// [`unwrap_unchecked()`](Result::unwrap_unchecked) might be an option, as well.
+///
+/// For even more details see the [Rust documentation].
+///
+/// [samples/rust/rust_minimal.rs]: srctreetree/samples/rust/rust_minimal.rs
+/// [`?`]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator
+/// [`match`]: https://doc.rust-lang.org/reference/expressions/match-expr.html
+/// [`BUG()`]: https://docs.kernel.org/process/deprecated.html#bug-and-bug-on
+/// [`if let`]: https://doc.rust-lang.org/reference/expressions/if-expr.html#if-let-expressions
+/// [Rust documentation]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html
 pub type Result<T = (), E = Error> = core::result::Result<T, E>;
 
 /// Converts an integer as returned by a C kernel function to an error if it's negative, and
Signature · 1 line
2.48.0
reviewer
#1 lore raw
Quoted 131 lines · Dirk Behme

Extend the Result documentation by some guidelines and examples how to handle Result error cases gracefully. And how to not handle them.

While at it fix one missing Result link in the existing documentation.

---

Changes in v4:
* Drop the expect() example and put the slightly rephrased unwrap()/expect() description below the ?-operator example (Alice & Miguel)

Changes in v3:
* Slight rephrase regarding panic() vs BUG(), whitespace and newline fixes, use srctree/ syntax, add Rust reference link for Result(), evaluate the result of the examples etc. (Miguel)

Changes in v2:
* Improve the linkage (Daniel & Alice)
* Reformat the examples, add if let, drop "automatically", call the example(), improve the formatting, etc (Miguel)

 rust/kernel/error.rs | 113 ++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 112 insertions(+), 1 deletion(-)
rust/kernel/error.rs +93 -1
index 0b01975c2286c..b4e59feb17a7f 100644
@@ -254,8 +254,119 @@ fn from(e: core::convert::Infallible) -> Error {
 /// [`Error`] as its error type.
 ///
 /// Note that even if a function does not return anything when it succeeds,
-/// it should still be modeled as returning a `Result` rather than
+/// it should still be modeled as returning a [`Result`] rather than
 /// just an [`Error`].
+///
+/// Calling a function that returns [`Result`] needs the caller to handle
+/// the returned [`Result`].
+///
+/// This can be done "manually" by using [`match`]. Using [`match`] to decode
+/// the [`Result`] is similar to C where all the return value decoding and the
+/// error handling is done explicitly by writing handling code for each
+/// error to cover. Using [`match`] the error and success handling can be
+/// implemented in all detail as required. For example (inspired by
+/// [samples/rust/rust_minimal.rs]):
+///
+/// ```
+/// fn example() -> Result {
+///     let mut numbers = KVec::new();
+///
+///     match numbers.push(72, GFP_KERNEL) {
+///         Err(e) => {
+///             pr_err!("Error pushing 72: {e:?}");
+///             return Err(e.into());
+///         }
+///         // Do nothing, continue.
+///         Ok(()) => (),
+///     }
+///
+///     match numbers.push(108, GFP_KERNEL) {
+///         Err(e) => {
+///             pr_err!("Error pushing 108: {e:?}");
+///             return Err(e.into());
+///         }
+///         // Do nothing, continue.
+///         Ok(()) => (),
+///     }
+///
+///     match numbers.push(200, GFP_KERNEL) {
+///         Err(e) => {
+///             pr_err!("Error pushing 200: {e:?}");
+///             return Err(e.into());
+///         }
+///         // Do nothing, continue.
+///         Ok(()) => (),
+///     }
+///
+///     Ok(())
+/// }
+/// # example()?;
+/// # Ok::<(), Error>(())
+/// ```
+///
+/// An alternative to be more concise is the [`if let`] syntax:
+///
+/// ```
+/// fn example() -> Result {
+///     let mut numbers = KVec::new();
+///
+///     if let Err(e) = numbers.push(72, GFP_KERNEL) {
+///         pr_err!("Error pushing 72: {e:?}");
+///         return Err(e.into());
+///     }
+///
+///     if let Err(e) = numbers.push(108, GFP_KERNEL) {
+///         pr_err!("Error pushing 108: {e:?}");
+///         return Err(e.into());
+///     }
+///
+///     if let Err(e) = numbers.push(200, GFP_KERNEL) {
+///         pr_err!("Error pushing 200: {e:?}");
+///         return Err(e.into());
+///     }
+///
+///     Ok(())
+/// }
+/// # example()?;
+/// # Ok::<(), Error>(())
+/// ```
+///
+/// Instead of these verbose [`match`]/[`if let`] the [`?`]-operator can
+/// be used to handle the [`Result`]. Using the [`?`]-operator is often
+/// the best choice to handle [`Result`] in a non-verbose way as done in
+/// [samples/rust/rust_minimal.rs]:
+///
+/// ```
+/// fn example() -> Result {
+///     let mut numbers = KVec::new();
+///     numbers.push(72, GFP_KERNEL)?;
+///     numbers.push(108, GFP_KERNEL)?;
+///     numbers.push(200, GFP_KERNEL)?;
+///     Ok(())
+/// }
+/// # example()?;
+/// # Ok::<(), Error>(())
+/// ```
+/// Another possibility is to call [`unwrap()`](Result::unwrap) or

rust/kernel/error.rs fn from(e: core::convert::Infallible) -> Error { · line 360

Quoted 10 lines
rust/kernel/error.rs +10 -0
+/// [`expect()`](Result::expect). However, use of these functions is
+/// *heavily discouraged* in the kernel because they trigger a Rust
+/// [`panic`] if an error happens, which may destabilize the system or
+/// entirely break it as a result -- just like the C [`BUG()`] macro.
+/// Please see the documentation for the C macro [`BUG()`] for guidance
+/// on when to use these functions. Alternatively, depending on the use
+/// case, using [`unwrap_or()`](Result::unwrap_or),
+/// [`unwrap_or_else()`](Result::unwrap_or_else),
+/// [`unwrap_or_default()`](Result::unwrap_or_default) or
+/// [`unwrap_unchecked()`](Result::unwrap_unchecked) might be an option, as well.

This sounds like unwrap_or() and friends are just as bad as unwrap(), but in reality they aren't since they don't panic. Maybe a paragraph break could be nice?

Otherwise looks good!

Alice

author
#2 lore raw
Quoted 138 lines · Alice Ryhl
Quoted 137 lines · Dirk Behme

Extend the Result documentation by some guidelines and examples how to handle Result error cases gracefully. And how to not handle them.

While at it fix one missing Result link in the existing documentation.

---

Changes in v4:
* Drop the expect() example and put the slightly rephrased unwrap()/expect() description below the ?-operator example (Alice & Miguel)

Changes in v3:
* Slight rephrase regarding panic() vs BUG(), whitespace and newline fixes, use srctree/ syntax, add Rust reference link for Result(), evaluate the result of the examples etc. (Miguel)

Changes in v2:
* Improve the linkage (Daniel & Alice)
* Reformat the examples, add if let, drop "automatically", call the example(), improve the formatting, etc (Miguel)

 rust/kernel/error.rs | 113 ++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 112 insertions(+), 1 deletion(-)
rust/kernel/error.rs +99 -1
index 0b01975c2286c..b4e59feb17a7f 100644
@@ -254,8 +254,119 @@ fn from(e: core::convert::Infallible) -> Error {
 /// [`Error`] as its error type.
 ///
 /// Note that even if a function does not return anything when it succeeds,
-/// it should still be modeled as returning a `Result` rather than
+/// it should still be modeled as returning a [`Result`] rather than
 /// just an [`Error`].
+///
+/// Calling a function that returns [`Result`] needs the caller to handle
+/// the returned [`Result`].
+///
+/// This can be done "manually" by using [`match`]. Using [`match`] to decode
+/// the [`Result`] is similar to C where all the return value decoding and the
+/// error handling is done explicitly by writing handling code for each
+/// error to cover. Using [`match`] the error and success handling can be
+/// implemented in all detail as required. For example (inspired by
+/// [samples/rust/rust_minimal.rs]):
+///
+/// ```
+/// fn example() -> Result {
+///     let mut numbers = KVec::new();
+///
+///     match numbers.push(72, GFP_KERNEL) {
+///         Err(e) => {
+///             pr_err!("Error pushing 72: {e:?}");
+///             return Err(e.into());
+///         }
+///         // Do nothing, continue.
+///         Ok(()) => (),
+///     }
+///
+///     match numbers.push(108, GFP_KERNEL) {
+///         Err(e) => {
+///             pr_err!("Error pushing 108: {e:?}");
+///             return Err(e.into());
+///         }
+///         // Do nothing, continue.
+///         Ok(()) => (),
+///     }
+///
+///     match numbers.push(200, GFP_KERNEL) {
+///         Err(e) => {
+///             pr_err!("Error pushing 200: {e:?}");
+///             return Err(e.into());
+///         }
+///         // Do nothing, continue.
+///         Ok(()) => (),
+///     }
+///
+///     Ok(())
+/// }
+/// # example()?;
+/// # Ok::<(), Error>(())
+/// ```
+///
+/// An alternative to be more concise is the [`if let`] syntax:
+///
+/// ```
+/// fn example() -> Result {
+///     let mut numbers = KVec::new();
+///
+///     if let Err(e) = numbers.push(72, GFP_KERNEL) {
+///         pr_err!("Error pushing 72: {e:?}");
+///         return Err(e.into());
+///     }
+///
+///     if let Err(e) = numbers.push(108, GFP_KERNEL) {
+///         pr_err!("Error pushing 108: {e:?}");
+///         return Err(e.into());
+///     }
+///
+///     if let Err(e) = numbers.push(200, GFP_KERNEL) {
+///         pr_err!("Error pushing 200: {e:?}");
+///         return Err(e.into());
+///     }
+///
+///     Ok(())
+/// }
+/// # example()?;
+/// # Ok::<(), Error>(())
+/// ```
+///
+/// Instead of these verbose [`match`]/[`if let`] the [`?`]-operator can
+/// be used to handle the [`Result`]. Using the [`?`]-operator is often
+/// the best choice to handle [`Result`] in a non-verbose way as done in
+/// [samples/rust/rust_minimal.rs]:
+///
+/// ```
+/// fn example() -> Result {
+///     let mut numbers = KVec::new();
+///     numbers.push(72, GFP_KERNEL)?;
+///     numbers.push(108, GFP_KERNEL)?;
+///     numbers.push(200, GFP_KERNEL)?;
+///     Ok(())
+/// }
+/// # example()?;
+/// # Ok::<(), Error>(())
+/// ```
+/// Another possibility is to call [`unwrap()`](Result::unwrap) or
+/// [`expect()`](Result::expect). However, use of these functions is
+/// *heavily discouraged* in the kernel because they trigger a Rust
+/// [`panic`] if an error happens, which may destabilize the system or
+/// entirely break it as a result -- just like the C [`BUG()`] macro.
+/// Please see the documentation for the C macro [`BUG()`] for guidance
+/// on when to use these functions. Alternatively, depending on the use
Quoted 8 lines

rust/kernel/error.rs fn from(e: core::convert::Infallible) -> Error { · line 360

Quoted 4 lines
rust/kernel/error.rs +4 -0
+/// case, using [`unwrap_or()`](Result::unwrap_or),
+/// [`unwrap_or_else()`](Result::unwrap_or_else),
+/// [`unwrap_or_default()`](Result::unwrap_or_default) or
+/// [`unwrap_unchecked()`](Result::unwrap_unchecked) might be an option, as well.

This sounds like unwrap_or() and friends are just as bad as unwrap(), but in reality they aren't since they don't panic. Maybe a paragraph break could be nice?

Yes, makes sense. Ack.

Let's see if a version 5 is required. If not, maybe Miguel could add that paragraph break before "Alternatively, depending ..." while applying?

Quoted 1 line

Otherwise looks good!

Thanks!

Dirk

#3 lore raw
In reply to Dirk Behme
Quoted 107 lines · Dirk Behme

Extend the Result documentation by some guidelines and examples how to handle Result error cases gracefully. And how to not handle them.

While at it fix one missing Result link in the existing documentation.

---

Changes in v4:
* Drop the expect() example and put the slightly rephrased unwrap()/expect() description below the ?-operator example (Alice & Miguel)

Changes in v3:
* Slight rephrase regarding panic() vs BUG(), whitespace and newline fixes, use srctree/ syntax, add Rust reference link for Result(), evaluate the result of the examples etc. (Miguel)

Changes in v2:
* Improve the linkage (Daniel & Alice)
* Reformat the examples, add if let, drop "automatically", call the example(), improve the formatting, etc (Miguel)

 rust/kernel/error.rs | 113 ++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 112 insertions(+), 1 deletion(-)
rust/kernel/error.rs +70 -1
index 0b01975c2286c..b4e59feb17a7f 100644
@@ -254,8 +254,119 @@ fn from(e: core::convert::Infallible) -> Error {
 /// [`Error`] as its error type.
 ///
 /// Note that even if a function does not return anything when it succeeds,
-/// it should still be modeled as returning a `Result` rather than
+/// it should still be modeled as returning a [`Result`] rather than
 /// just an [`Error`].
+///
+/// Calling a function that returns [`Result`] needs the caller to handle
+/// the returned [`Result`].
+///
+/// This can be done "manually" by using [`match`]. Using [`match`] to decode
+/// the [`Result`] is similar to C where all the return value decoding and the
+/// error handling is done explicitly by writing handling code for each
+/// error to cover. Using [`match`] the error and success handling can be
+/// implemented in all detail as required. For example (inspired by
+/// [samples/rust/rust_minimal.rs]):
+///
+/// ```
+/// fn example() -> Result {
+///     let mut numbers = KVec::new();
+///
+///     match numbers.push(72, GFP_KERNEL) {
+///         Err(e) => {
+///             pr_err!("Error pushing 72: {e:?}");
+///             return Err(e.into());
+///         }
+///         // Do nothing, continue.
+///         Ok(()) => (),
+///     }
+///
+///     match numbers.push(108, GFP_KERNEL) {
+///         Err(e) => {
+///             pr_err!("Error pushing 108: {e:?}");
+///             return Err(e.into());
+///         }
+///         // Do nothing, continue.
+///         Ok(()) => (),
+///     }
+///
+///     match numbers.push(200, GFP_KERNEL) {
+///         Err(e) => {
+///             pr_err!("Error pushing 200: {e:?}");
+///             return Err(e.into());
+///         }
+///         // Do nothing, continue.
+///         Ok(()) => (),
+///     }
+///
+///     Ok(())
+/// }
+/// # example()?;
+/// # Ok::<(), Error>(())
+/// ```
+///
+/// An alternative to be more concise is the [`if let`] syntax:
+///
+/// ```
+/// fn example() -> Result {
+///     let mut numbers = KVec::new();
+///
+///     if let Err(e) = numbers.push(72, GFP_KERNEL) {
+///         pr_err!("Error pushing 72: {e:?}");
+///         return Err(e.into());
+///     }
+///
+///     if let Err(e) = numbers.push(108, GFP_KERNEL) {
+///         pr_err!("Error pushing 108: {e:?}");
+///         return Err(e.into());
+///     }
+///
+///     if let Err(e) = numbers.push(200, GFP_KERNEL) {
+///         pr_err!("Error pushing 200: {e:?}");
+///         return Err(e.into());
+///     }
+///

rust/kernel/error.rs fn from(e: core::convert::Infallible) -> Error { · line 337

Quoted 10 lines
rust/kernel/error.rs +10 -0
+///     Ok(())
+/// }
+/// # example()?;
+/// # Ok::<(), Error>(())
+/// ```
+///
+/// Instead of these verbose [`match`]/[`if let`] the [`?`]-operator can
+/// be used to handle the [`Result`]. Using the [`?`]-operator is often
+/// the best choice to handle [`Result`] in a non-verbose way as done in
+/// [samples/rust/rust_minimal.rs]:

All examples above feature a pr_err and then return the error. Then the ?-operator is just called less verbose. Maybe it makes sense to also state that it then does not print anything and possible also show that it could be logged at this place with inspect_err.
Though I remember that usage of inspect_err got discussed at kangrejos (rfl-conference) but don’t fully remember the outcome, think it was something like use it sparingly.

Thanks,
Fiona

Quoted 37 lines
rust/kernel/error.rs +32 -0
+///
+/// ```
+/// fn example() -> Result {
+///     let mut numbers = KVec::new();
+///     numbers.push(72, GFP_KERNEL)?;
+///     numbers.push(108, GFP_KERNEL)?;
+///     numbers.push(200, GFP_KERNEL)?;
+///     Ok(())
+/// }
+/// # example()?;
+/// # Ok::<(), Error>(())
+/// ```
+/// Another possibility is to call [`unwrap()`](Result::unwrap) or
+/// [`expect()`](Result::expect). However, use of these functions is
+/// *heavily discouraged* in the kernel because they trigger a Rust
+/// [`panic`] if an error happens, which may destabilize the system or
+/// entirely break it as a result -- just like the C [`BUG()`] macro.
+/// Please see the documentation for the C macro [`BUG()`] for guidance
+/// on when to use these functions. Alternatively, depending on the use
+/// case, using [`unwrap_or()`](Result::unwrap_or),
+/// [`unwrap_or_else()`](Result::unwrap_or_else),
+/// [`unwrap_or_default()`](Result::unwrap_or_default) or
+/// [`unwrap_unchecked()`](Result::unwrap_unchecked) might be an option, as well.
+///
+/// For even more details see the [Rust documentation].
+///
+/// [samples/rust/rust_minimal.rs]: srctreetree/samples/rust/rust_minimal.rs
+/// [`?`]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator
+/// [`match`]: https://doc.rust-lang.org/reference/expressions/match-expr.html
+/// [`BUG()`]: https://docs.kernel.org/process/deprecated.html#bug-and-bug-on
+/// [`if let`]: https://doc.rust-lang.org/reference/expressions/if-expr.html#if-let-expressions
+/// [Rust documentation]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html
 pub type Result<T = (), E = Error> = core::result::Result<T, E>;
 
 /// Converts an integer as returned by a C kernel function to an error if it's negative, and
Signature · 1 line
2.48.0
author
#4 lore raw

Hi Fiona,

Quoted 117 lines · Fiona Behrens
Quoted 115 lines · Dirk Behme

Extend the Result documentation by some guidelines and examples how to handle Result error cases gracefully. And how to not handle them.

While at it fix one missing Result link in the existing documentation.

---

Changes in v4:
* Drop the expect() example and put the slightly rephrased unwrap()/expect() description below the ?-operator example (Alice & Miguel)

Changes in v3:
* Slight rephrase regarding panic() vs BUG(), whitespace and newline fixes, use srctree/ syntax, add Rust reference link for Result(), evaluate the result of the examples etc. (Miguel)

Changes in v2:
* Improve the linkage (Daniel & Alice)
* Reformat the examples, add if let, drop "automatically", call the example(), improve the formatting, etc (Miguel)

 rust/kernel/error.rs | 113 ++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 112 insertions(+), 1 deletion(-)
rust/kernel/error.rs +78 -1
index 0b01975c2286c..b4e59feb17a7f 100644
@@ -254,8 +254,119 @@ fn from(e: core::convert::Infallible) -> Error {
 /// [`Error`] as its error type.
 ///
 /// Note that even if a function does not return anything when it succeeds,
-/// it should still be modeled as returning a `Result` rather than
+/// it should still be modeled as returning a [`Result`] rather than
 /// just an [`Error`].
+///
+/// Calling a function that returns [`Result`] needs the caller to handle
+/// the returned [`Result`].
+///
+/// This can be done "manually" by using [`match`]. Using [`match`] to decode
+/// the [`Result`] is similar to C where all the return value decoding and the
+/// error handling is done explicitly by writing handling code for each
+/// error to cover. Using [`match`] the error and success handling can be
+/// implemented in all detail as required. For example (inspired by
+/// [samples/rust/rust_minimal.rs]):
+///
+/// ```
+/// fn example() -> Result {
+///     let mut numbers = KVec::new();
+///
+///     match numbers.push(72, GFP_KERNEL) {
+///         Err(e) => {
+///             pr_err!("Error pushing 72: {e:?}");
+///             return Err(e.into());
+///         }
+///         // Do nothing, continue.
+///         Ok(()) => (),
+///     }
+///
+///     match numbers.push(108, GFP_KERNEL) {
+///         Err(e) => {
+///             pr_err!("Error pushing 108: {e:?}");
+///             return Err(e.into());
+///         }
+///         // Do nothing, continue.
+///         Ok(()) => (),
+///     }
+///
+///     match numbers.push(200, GFP_KERNEL) {
+///         Err(e) => {
+///             pr_err!("Error pushing 200: {e:?}");
+///             return Err(e.into());
+///         }
+///         // Do nothing, continue.
+///         Ok(()) => (),
+///     }
+///
+///     Ok(())
+/// }
+/// # example()?;
+/// # Ok::<(), Error>(())
+/// ```
+///
+/// An alternative to be more concise is the [`if let`] syntax:
+///
+/// ```
+/// fn example() -> Result {
+///     let mut numbers = KVec::new();
+///
+///     if let Err(e) = numbers.push(72, GFP_KERNEL) {
+///         pr_err!("Error pushing 72: {e:?}");
+///         return Err(e.into());
+///     }
+///
+///     if let Err(e) = numbers.push(108, GFP_KERNEL) {
+///         pr_err!("Error pushing 108: {e:?}");
+///         return Err(e.into());
+///     }
+///
+///     if let Err(e) = numbers.push(200, GFP_KERNEL) {
+///         pr_err!("Error pushing 200: {e:?}");
+///         return Err(e.into());
+///     }
+///
+///     Ok(())
+/// }
+/// # example()?;
+/// # Ok::<(), Error>(())
+/// ```
+///
+/// Instead of these verbose [`match`]/[`if let`] the [`?`]-operator can
+/// be used to handle the [`Result`]. Using the [`?`]-operator is often
Quoted 8 lines

rust/kernel/error.rs fn from(e: core::convert::Infallible) -> Error { · line 337

Quoted 2 lines
rust/kernel/error.rs +2 -0
+/// the best choice to handle [`Result`] in a non-verbose way as done in
+/// [samples/rust/rust_minimal.rs]:

All examples above feature a pr_err and then return the error. Then the ?-operator is just called less verbose. Maybe it makes sense to also state that it then does not print anything and possible also show that it could be logged at this place with inspect_err.
Though I remember that usage of inspect_err got discussed at kangrejos (rfl-conference) but don’t fully remember the outcome, think it was something like use it sparingly.

Yes, we talked about that. If I remember correctly the conclusion was somehow that the caller is responsible to report correctly about possible errors he gets back. Like in C. And yes, I think the samples/rust/rust_minimal.rs used here is exactly an example where this is *not* the case. This is what I called "silent" errors.

The idea of this patch is "don't use unwrap/expect as it might panic". And yes, we need some explanation for using the ?-operator correctly. Esp. to avoid these "silent" errors.

But would it be ok for you to do this in two steps? I.e. having this "no unwrap/expect" patch. And then in a second step a "use ? correctly" explanation?

Best regards,

Dirk

Reviewed-by
#5 lore raw

Hi,

Quoted 22 lines · Dirk Behme

Hi Fiona,

Quoted 13 lines · Fiona Behrens

rust/kernel/error.rs fn from(e: core::convert::Infallible) -> Error { · line 337

Quoted 6 lines · Dirk Behme
rust/kernel/error.rs +6 -0
+/// ```
+///
+/// Instead of these verbose [`match`]/[`if let`] the [`?`]-operator can
+/// be used to handle the [`Result`]. Using the [`?`]-operator is often
+/// the best choice to handle [`Result`] in a non-verbose way as done in
+/// [samples/rust/rust_minimal.rs]:

All examples above feature a pr_err and then return the error. Then the ?-operator is just called less verbose. Maybe it makes sense to also state that it then does not print anything and possible also show that it could be logged at this place with inspect_err.
Though I remember that usage of inspect_err got discussed at kangrejos (rfl-conference) but don’t fully remember the outcome, think it was something like use it sparingly.

Yes, we talked about that. If I remember correctly the conclusion was somehow that the caller is responsible to report correctly about possible errors he gets back. Like in C. And yes, I think the samples/rust/rust_minimal.rs used here is exactly an example where this is *not* the case. This is what I called "silent" errors.

Quoted 7 lines

The idea of this patch is "don't use unwrap/expect as it might panic". And yes, we need some explanation for using the ?-operator correctly. Esp. to avoid these "silent" errors.

But would it be ok for you to do this in two steps? I.e. having this "no unwrap/expect" patch. And then in a second step a "use ? correctly" explanation?

My idea was that having a comment that states that this will not print something avoids confusion, as all examples above to print a message and then this is just a alternative and nothing get’s said about them being “silent”. I am fine doing that later, just shouldn’t forget it.

In case you want to first merge this and then new patch for the silent explanation:

Thanks,
Fiona

Quoted 4 lines

Best regards,

Dirk

Applied
#6 lore raw
In reply to Dirk Behme
Quoted 8 lines · Dirk Behme

Extend the Result documentation by some guidelines and examples how to handle Result error cases gracefully. And how to not handle them.

While at it fix one missing Result link in the existing documentation.

Applied to rust-next -- thanks everyone!

[ Moved links out-of-line for improved readability. Fixed srctree
link. Sorted out-of-line links. Added newlines for consistency with other docs. Applied paragraph break suggestion. Reworded slightly the docs in a couple places. Added Markdown.

In addition, added #[allow(clippy::single_match) for the first example. It cannot be an expect since due to a difference introduced in Rust 1.85.0 when there are comments in the arms of the match. Reported it upstream, but it was intended:

https://github.com/rust-lang/rust-clippy/issues/14418

Perhaps Clippy will lint about it in the future, but without autofix:

https://github.com/rust-lang/rust-clippy/pull/14420

- Miguel ]

Cheers,
Miguel