Riddle: How to solve "cannot return value referencing temporary value"

Continuing the discussion from Concatenating arrays:

Doing the reverse operation, I ran into this confusing error (at least it did confuse me):

pub fn split_array(full: &[u8; 200]) -> (&[u8; 100], &[u8; 100]) {
    (
      &full[0..100].try_into().unwrap(),
      &full[100..200].try_into().unwrap(),
    )
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0515]: cannot return value referencing temporary value
 --> src/lib.rs:2:5
  |
2 | /     (
3 | |       &full[0..100].try_into().unwrap(),
  | |        -------------------------------- temporary value created here
4 | |       &full[100..200].try_into().unwrap(),
5 | |     )
  | |_____^ returns a value referencing data owned by the current function

error[E0515]: cannot return value referencing temporary value
 --> src/lib.rs:2:5
  |
2 | /     (
3 | |       &full[0..100].try_into().unwrap(),
4 | |       &full[100..200].try_into().unwrap(),
  | |        ---------------------------------- temporary value created here
5 | |     )
  | |_____^ returns a value referencing data owned by the current function

For more information about this error, try `rustc --explain E0515`.
error: could not compile `playground` due to 2 previous errors

After I thought I had to use std::ops::Index to get the lifetimes right, I found the solution:

Click on blurred content to reveal.

 pub fn split_array(full: &[u8; 200]) -> (&[u8; 100], &[u8; 100]) {
     (
-      &full[0..100].try_into().unwrap(),
+      (&full[0..100]).try_into().unwrap(),
-      &full[100..200].try_into().unwrap(),
+      (&full[100..200]).try_into().unwrap(),
     )
 }

(Playground)

1 Like

It's an operator precedence thing. Prefix operators have lower precedence than postfix operators, thus &foo.bar() is &(foo.bar()), which does (unintentionally) reference a temporary.

Yeah, it makes sense. I just didn't remember/notice that when "out of habit" writing &x[y].

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.