```rust
// Good
+fn main() {
+ let s: &str = ...;
+ if let Some(contents) = string_literal_contents(s) {
+
+ }
+}
+
fn string_literal_contents(s: &str) -> Option<&str> {
if s.starts_with('"') && s.ends_with('"') {
Some(&s[1..s.len() - 1])
}
}
-fn foo() {
+// Not as good
+fn main() {
let s: &str = ...;
- if let Some(contents) = string_literal_contents(s) {
-
+ if is_string_literal(s) {
+ let contents = &s[1..s.len() - 1];
}
}
-// Not as good
fn is_string_literal(s: &str) -> bool {
s.starts_with('"') && s.ends_with('"')
}
-
-fn foo() {
- let s: &str = ...;
- if is_string_literal(s) {
- let contents = &s[1..s.len() - 1];
- }
-}
```
In the "Not as good" version, the precondition that `1` is a valid char boundary is checked in `is_string_literal` and used in `foo`.