I'm working on some coding challenges to learn Rust. In JavaScript it's pretty straightforward but in Rust I've had issues.
Here's what the JS would look like:
// Decode the message by reversing the words
function reverseWords(message) {
return message.join("").split(" ").reverse().join(" ").split("");
}
This is how far I could get in Rust solving the same problem:
// Decode the message by reversing the words
fn reverse_words(message: Vec<&str>) -> Vec<&str> {
let temp_a = message.join("");
let mut words: Vec<&str> = temp_a.split(" ").collect();
words.reverse();
let new_temp = words.join(" ");
let result = new_temp.split("").collect();
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn two_words() {
let input = "thief cake".split("").collect();
let actual = reverse_words(input).join("");
let expected = "cake thief";
assert_eq!(actual, expected);
}
}
This results in the following error:
error[E0515]: cannot return value referencing local variable `new_temp`
--> src/reverse_words/mod.rs:13:5
|
11 | let result = new_temp.split("").collect();
| ------------------ `new_temp` is borrowed here
12 |
13 | result
| ^^^^^^ returns a value referencing data owned by the current function
For more information about this error, try `rustc --explain E0515`.
I've tried all sorts of solutions to get around this ownership problem but there's clearly something I'm not understanding.
Here's a link to the playground if it helps: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=d75a3894112c188780b9805661510c46