New to rust... error: "borrowed value does not live long enough"

demo by RefCell<T> and the Interior Mutability Pattern - The Rust Programming Language

error :

  if let Some(msg) = mock_messenger.sent_messages.borrow().get(0) {
      println!("value: {:?}", msg);
  } else {
      println!("Get None.");
  }

success:

  if let Some(msg) = mock_messenger.sent_messages.clone().borrow().get(0) {
      println!("value: {:?}", msg);
  } else {
      println!("Get None.");
  }

also success:

match mock_messenger.sent_messages.borrow().get(0) {
    Some(msg) => println!("{:?}", msg),
    _ => println!("{:?}", "err"),
};

i just wonder where is the difference...

After doing a clone clone, you borrow a cloned value that you (your scope) own. Otherwise you borrow a value that you don’t own.

Thank you for reply. I add an example, it's also "borrow a value that don't own" and no error...

Well, compiler tells the truth: Borrowed value doesn’t live long enough. I don’t really know what to tell you, maybe someone will give you a better explanation :wink:

In Rust variables are semantically meaningful, and foo().bar() is a different thing than let tmp = foo(); tmp.bar().

In your case the value (a lock) returned by borrow() is not saved anywhere, and that's why doesn't live long enough. It exists only in a temporary scope of an expression, and that temporary scope varies depending on how the expression is constructed/used (that's why match works more often than other constructs), but it's best to be explicit about which values aren't supposed to be temporary.

If you change:

if let Some(msg) = mock_messenger.sent_messages.borrow().get(0)

to

let tmp = mock_messenger.sent_messages.borrow();
if let Some(msg) = tmp.get(0)

it should work, because then get(0) will be borrowing from tmp that won't go away until the end of the outer scope, instead of a temporary object created mid-way in an expression without non-temporary storage.

3 Likes

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.