# Why is there a temporary created here?

**URL:** <https://users.rust-lang.org/t/why-is-there-a-temporary-created-here/66060>\
**Category:** help\
**Created:** [October 18, 2021, 10:14am UTC](https://users.rust-lang.org/t/why-is-there-a-temporary-created-here/66060 "2021-10-18T10:14:15Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![dbtale](https://avatars.discourse-cdn.com/v4/letter/d/c4cdca/32.png) [@dbtale](https://users.rust-lang.org/u/dbtale)\
**Post date:** [October 18, 2021, 10:14am UTC](https://users.rust-lang.org/t/why-is-there-a-temporary-created-here/66060/1 "2021-10-18T10:14:15Z")

</div>

```rust
use std::sync::Mutex;

pub struct First {
    amutex:Mutex<Second>,
}

pub struct Second {
    avec:Vec<u8>,
}

impl First {
    fn getRange(&self,start:usize,stop:usize) -> &[u8] {
        let refvec=&self.amutex.lock().unwrap();
        &(*refvec).avec.as_slice()[start..stop]
    }
}

fn main() {
    let f=First {
        amutex:Mutex::new(Second {
           avec:vec![0,2,4,6,8,10], 
        }),
    };
    let range=f.getRange(1,3);
    for dataitem in range {
        println!("{}",dataitem);
    }
}

```

([Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=8289e62c1fee0738aaea7a15bab9d1db))

Errors:

```rust
   Compiling playground v0.0.1 (/playground)
error[E0515]: cannot return value referencing temporary value
  --> src/main.rs:14:9
   |
13 | let refvec=&self.amutex.lock().unwrap();
   | --------------------------- temporary value created here
14 | &(*refvec).avec.as_slice()[start..stop]
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 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 previous error

```

I was under the impression that I have created a reference. I assume the mutexguard is the temporary created but that does not need to survive for this code to work, according to my understanding.

---

<div class="post-metadata">

**Author:** ![Yandros](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/yandros/32/8136_2.png) [@Yandros](https://users.rust-lang.org/u/Yandros)\
**Post date:** [October 18, 2021, 10:52am UTC](https://users.rust-lang.org/t/why-is-there-a-temporary-created-here/66060/2 "2021-10-18T10:52:07Z")

</div>

> [@dbtale](#):
>
> I assume the mutexguard is the temporary

✅

> [@dbtale](#):
>
> but that does not need to survive for this code to work

❌ 🙃

Indeed, you want _shared_, and in this instance, immutable, access to the `Second`('s `Vec`) instance.  
But if the lock guard is released, then Rust cannot guarantee lack of mutation between the moment where it is released and the moment where you are looking at the `start .. stop` range of that vec, hence the error.

* * *

There are, in general, three kinds of solutions for your problem, here:

- you can expose the `Mutex` (or at least a locking function) and have `getRange` be a method on `Second` (or the guard yielded by the locking function):

- You can offer a callback / scoped API, which allows you to have your own code run after the caller's, which means you can give access to the inner borrow to the caller:

- And finally, you can, for a simple case such as this one, offer "sugar" for the previous callback-based API by offering your own lock guard:

where `adhoc_deref` would be the `Deref` counterpart of [scopeguard - Rust](https://docs.rs/scopeguard), which oddly enough, does not exist yet:

```rust
pub
struct AdhocDeref<
    Guard,
    Field : ?Sized,
    Deref : Fn(&Guard) -> &Field,
>
{
    pub guard: Guard,
    pub deref_with: Deref,
    pub _phantom: ::core::marker::PhantomData<fn(&Guard) -> &Field>,
}

impl<
    Guard,
    Field : ?Sized,
    Deref : Fn(&Guard) -> &Field,
>
    ::core::ops::Deref
for
    AdhocDeref<Guard, Field, Deref>
{
    type Target = Field;

    #[inline]
    fn deref (self: &'_ Self)
      -> &'_ Field
    {
        (self.deref_with)(&self.guard)
    }
}

```

- [Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a906674f0e08ac7197b57f2664107ff7)

---

<div class="post-metadata">

**Author:** ![dbtale](https://avatars.discourse-cdn.com/v4/letter/d/c4cdca/32.png) [@dbtale](https://users.rust-lang.org/u/dbtale)\
**Post date:** [October 18, 2021, 11:14am UTC](https://users.rust-lang.org/t/why-is-there-a-temporary-created-here/66060/3 "2021-10-18T11:14:29Z")

</div>

Thanks for this very informative reply. The second recommendation was a perfect idea for my problem. I went with that.

---

<div class="post-metadata">

**Author:** ![H2CO3](https://avatars.discourse-cdn.com/v4/letter/h/b5ac83/32.png) [@H2CO3](https://users.rust-lang.org/u/H2CO3)\
**Post date:** [October 18, 2021, 11:48am UTC](https://users.rust-lang.org/t/why-is-there-a-temporary-created-here/66060/4 "2021-10-18T11:48:40Z")

</div>

> [@dbtale](#):
>
> I assume the mutexguard is the temporary created but that does not need to survive for this code to work

In general, _the very point_ of "guard" objects is that they are the token with which you will be able to do useful things to the guarded object. It wouldn't make sense for a `Mutex` to hand out guards if they didn't actually enforce the invariant of the mutex (i.e. that it is held while someone is poking around in the locked object).

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [January 16, 2022, 11:49am UTC](https://users.rust-lang.org/t/why-is-there-a-temporary-created-here/66060/5 "2022-01-16T11:49:02Z")

</div>

Closed on January 16, 2022, 11:49am UTC

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.
