My requirement is to return an array of 5 string slices in my calc method. In my main method, I create any arbitrary 10 element array I want for my program.
I pass this array an a parameter to the calc method, it does some calculations, I am just trying to figure out how I can an array of 5 string slices as I am required to.
As I can return either one of two arrays (of type string slices) based on calculations I get, I am trying to return the appropriate array using an if else if ladder.
fn main()
{
let arr:[u32;10] = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
let output:[&str;5] = calc(arr);
println!("{:?}", output);
}
fn calc(arr: [u32;10]) -> [&'static str; 5]
{
let mut str1:[&str;5] = ["", "", "", "", ""];
let mut str2:[&str;5] = ["", "", "", "", ""];
let mut arr1 = [0; 5];
let mut arr2 = [0; 5];
let mut sorted_arr1 = arr1;
let mut sorted_arr2 = arr2;
sorted_arr1.sort();
sorted_arr2.sort();
for i in 0..5
{
arr1[i] = arr[i];
arr2[i] = arr[i+5];
}
//L for less than, E for equal to, G for greater than
for i in 0..5
{
if arr1[i] < 5 {
str1[i] = &format!("{}{}", arr1[i], "L").to_string();
}
else if arr1[i] == 5 {
str1[i] = &format!("{}{}", arr1[i], "E").to_string();
}
else if arr1[i] > 5 {
str1[i] = &format!("{}{}", arr1[i], "G").to_string();
}
if arr2[i] < 5 {
str2[i] = &format!("{}{}", arr2[i], "L").to_string();
}
else if arr2[i] == 5 {
str2[i] = &format!("{}{}", arr2[i], "E").to_string();
}
else if arr2[i] > 5 {
str2[i] = &format!("{}{}", arr2[i], "G").to_string();
}
}
let foo1_winner = foo1();
let foo2_winner = foo2();
if foo1_winner == sorted_arr1 {
return str1;
}
else if foo1_winner == sorted_arr2 {
return str2;
}
else if foo2_winner == sorted_arr1 {
return str1;
}
else if foo2_winner == sorted_arr2 {
return str2;
}
return str1;
}
fn foo1() -> [u32; 5]
{
[1,2,3,4,5]
}
fn foo2() -> [u32; 5]
{
[6,7,8,9,10]
}
For all my return statements I get an compilation error like this
/*
error[E0515]: cannot return value referencing temporary value
--> stack.rs:71:16
|
43 | str1[i] = &format!("{}{}", arr1[i], "L").to_string();
| ----------------------------------------- temporary value created here
...
71 | return str1;
| ^^^^ returns a value referencing data owned by the current function
*/
I have searched for solutions to this problem but been able to make sense of anything I have read. How do I fix this issue? Any help is appreciated, thanks.