rust/tests/ui/manual_unwrap_or.fixed

140 lines
2.9 KiB
Rust
Raw Normal View History

// run-rustfix
#![allow(dead_code)]
2020-10-22 15:46:10 -05:00
#![allow(unused_variables)]
fn option_unwrap_or() {
// int case
Some(1).unwrap_or(42);
2020-10-11 15:55:05 -05:00
// int case reversed
Some(1).unwrap_or(42);
// richer none expr
Some(1).unwrap_or(1 + 42);
// multiline case
#[rustfmt::skip]
Some(1).unwrap_or({
42 + 42
+ 42 + 42 + 42
+ 42 + 42 + 42
});
// string case
Some("Bob").unwrap_or("Alice");
// don't lint
match Some(1) {
Some(i) => i + 2,
None => 42,
};
match Some(1) {
Some(i) => i,
None => return,
};
for j in 0..4 {
match Some(j) {
Some(i) => i,
None => continue,
};
match Some(j) {
Some(i) => i,
None => break,
};
}
// cases where the none arm isn't a constant expression
// are not linted due to potential ownership issues
// ownership issue example, don't lint
struct NonCopyable;
let mut option: Option<NonCopyable> = None;
match option {
Some(x) => x,
None => {
option = Some(NonCopyable);
// some more code ...
option.unwrap()
},
};
// ownership issue example, don't lint
let option: Option<&str> = None;
match option {
Some(s) => s,
None => &format!("{} {}!", "hello", "world"),
};
}
fn result_unwrap_or() {
// int case
2020-10-22 15:46:10 -05:00
Ok::<i32, &str>(1).unwrap_or(42);
2020-10-22 16:39:59 -05:00
// int case, scrutinee is a binding
let a = Ok::<i32, &str>(1);
a.unwrap_or(42);
2020-10-24 04:35:05 -05:00
// int case, suggestion must surround Result expr with parenthesis
(Ok(1) as Result<i32, &str>).unwrap_or(42);
2020-10-24 04:35:05 -05:00
// method call case, suggestion must not surround Result expr `s.method()` with parenthesis
struct S {}
impl S {
fn method(self) -> Option<i32> {
Some(42)
}
}
let s = S {};
s.method().unwrap_or(42);
// int case reversed
2020-10-22 15:46:10 -05:00
Ok::<i32, &str>(1).unwrap_or(42);
// richer none expr
2020-10-22 15:46:10 -05:00
Ok::<i32, &str>(1).unwrap_or(1 + 42);
// multiline case
#[rustfmt::skip]
2020-10-22 15:46:10 -05:00
Ok::<i32, &str>(1).unwrap_or({
42 + 42
+ 42 + 42 + 42
+ 42 + 42 + 42
});
// string case
2020-10-22 15:46:10 -05:00
Ok::<&str, &str>("Bob").unwrap_or("Alice");
// don't lint
2020-10-22 15:46:10 -05:00
match Ok::<i32, &str>(1) {
Ok(i) => i + 2,
Err(_) => 42,
};
2020-10-22 15:46:10 -05:00
match Ok::<i32, &str>(1) {
Ok(i) => i,
Err(_) => return,
};
for j in 0..4 {
2020-10-22 15:46:10 -05:00
match Ok::<i32, &str>(j) {
Ok(i) => i,
Err(_) => continue,
};
2020-10-22 15:46:10 -05:00
match Ok::<i32, &str>(j) {
Ok(i) => i,
Err(_) => break,
};
}
2020-10-22 15:46:10 -05:00
// don't lint, Err value is used
match Ok::<&str, &str>("Alice") {
Ok(s) => s,
Err(s) => s,
};
// could lint, but unused_variables takes care of it
match Ok::<&str, &str>("Alice") {
Ok(s) => s,
Err(s) => "Bob",
};
}
fn main() {}