Skip to content

Commit 7aaa845

Browse files
committed
docs(code-style-guide): Add section about unwraps
1 parent d0297b1 commit 7aaa845

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

modules/contributor/pages/code-style-guide.adoc

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -531,6 +531,41 @@ enum Error {
531531
. `unable to read config file from ...` to indicate that the file could not be loaded (for example because the file doesn't exist).
532532
. `unable to parse value ...` to indicate that parsing a user provided value failed (for example because it didn't conform to the expected syntax).
533533

534+
=== Using `unwrap`
535+
536+
Generally, it is not recommended to use `unwrap` (or any other method which consumes the error) in any fallible code path.
537+
Instead, proper error handling like above should be used.
538+
There are however cases, where it is fine to use `unwrap` or friends.
539+
540+
One such an example is when compiling regular expressions inside const/static environments.
541+
For such cases code must use `expect` instead of `unwrap` to provide additional context why a particular piece of code should never fail.
542+
543+
// Do we want to mention that this is enforced via clippy and that we actually enable that lint in our repos?
544+
545+
[TIP.code-rule,caption=Examples of correct code for this rule]
546+
====
547+
548+
[source,rust]
549+
----
550+
static VERSION_REGEX: LazyLock<Regex> = LazyLock::new(|| {
551+
Regex::new(r".*").expect("failed to compile regex")
552+
});
553+
----
554+
555+
====
556+
557+
[WARNING.code-rule,caption=Examples of incorrect code for this rule]
558+
====
559+
560+
[source,rust]
561+
----
562+
static VERSION_REGEX: LazyLock<Regex> = LazyLock::new(|| {
563+
Regex::new(r".*").unwrap()
564+
});
565+
----
566+
567+
====
568+
534569
== String formatting
535570

536571
=== Named versus unnamed format string identifiers
@@ -737,3 +772,27 @@ mod test {
737772
----
738773
739774
====
775+
776+
=== Using `unwrap`
777+
778+
The usage of `unwrap` in unit tests is not recommended for the same reasons as mentioned above, but allowed.
779+
780+
[TIP.code-rule,caption=Examples of correct code for this rule]
781+
====
782+
783+
[source,rust]
784+
----
785+
#[test]
786+
fn deserialize() {
787+
let input: String = serde_yaml::from_str("my string").expect("input string must deserialize");
788+
assert_eq(&input, "my string");
789+
}
790+
791+
#[test]
792+
fn serialize() {
793+
let serialized = serde_yaml::to_string(&String::from("my string")).unwrap();
794+
println!("{serialized}");
795+
}
796+
----
797+
798+
====

0 commit comments

Comments
 (0)