I'm working through the codewars katas, and came upon this problem:
fn divisors(num: i32) -> Result<Vec<i32>, &'static str> {
let mut d: Vec<i32> = Vec::new();
for n in 2..=(num / 2) + 1 {
if num % n == 0 {
d.push(n)
}
}
match d {
v if v.is_empty() => Err(format!("{} is prime!", num).as_str()),
_ => Ok(d),
}
}
When I try to compile this I get the following error:
error[E0515]: cannot return value referencing temporary value
--> src/lib.rs:11:30
|
11 | v if v.is_empty() => Err(format!("{} is prime!", num).as_str()),
| ^^^^----------------------------^^^^^^^^^^
| | |
| | temporary value created here
| returns a value referencing data owned by the current function
|
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
I get that this means I'm trying to return a reference to a slice of a String which no longer exists - because it's been destroyed, but how can I overcome this?
I want to return a Result whose Err value is a &str. Is that even a reasonable thing to do? At least I think that's what I want to do because of the following line in the instructions:
divisors(13); // should return Err("13 is prime")