# Idiomatic way to refer to reference or value

**URL:** <https://users.rust-lang.org/t/idiomatic-way-to-refer-to-reference-or-value/46533>\
**Category:** help\
**Created:** [July 29, 2020, 4:09am UTC](https://users.rust-lang.org/t/idiomatic-way-to-refer-to-reference-or-value/46533 "2020-07-29T04:09:16Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![diggyk](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/diggyk/32/16408_2.png) [@diggyk](https://users.rust-lang.org/u/diggyk)\
**Post date:** [July 29, 2020, 4:09am UTC](https://users.rust-lang.org/t/idiomatic-way-to-refer-to-reference-or-value/46533/1 "2020-07-29T04:09:16Z")

</div>

Hello! I'm still very new and trying to learn the right way to do things without just `cloning` my way out of a problem 😃

Suppose I have some structs struct:

```rust
struct Data {
    pub x: i32,
    pub y: i32, 
}

struct Agent {
   q: i32,
   r: i32,
}

impl Agent {
    pub fn get_data(&self) -> Data {
        Data { x: self.q, y: self.r }
    }

```

Now, suppose I have a method where someone can optionally send alternative `Data`:

```rust
fn do_stuff(agent: &Agent, data: Option<&Data>) {
    let our_data: &Data;
    if data.is_none() {
        our_data = &agent.get_data();
    } else {
        our_data = data.unwrap();
    }

    do_other_things(our_data);
    [...]
}

```

This doesn't work because `&robot.get_data()` creates a temporary value that goes out of scope. I know that one way I can fix this is to have the `do_stuff` function just taken an `Option<Data>` but then it seems like the called would need to call it with cloned `Data` since it can't just send a reference.

So how would people solve this problem?

---

<div class="post-metadata">

**Author:** ![L.F](https://avatars.discourse-cdn.com/v4/letter/l/43a26b/32.png) [@L.F](https://users.rust-lang.org/u/L.F)\
**Post date:** [July 29, 2020, 4:31am UTC](https://users.rust-lang.org/t/idiomatic-way-to-refer-to-reference-or-value/46533/2 "2020-07-29T04:31:21Z")

</div>

One simple way is to just move `do_other_things` inside the branches:

```rust
fn do_stuff(agent: &Agent, data: Option<&Data>) {
    match data {
        None => do_other_things(&agent.get_data()),
        Some(data) => do_other_things(data),
    }
}

```

---

<div class="post-metadata">

**Author:** ![Michael-F-Bryan](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/michael-f-bryan/32/28749_2.png) [@Michael-F-Bryan](https://users.rust-lang.org/u/Michael-F-Bryan)\
**Post date:** [July 29, 2020, 4:31am UTC](https://users.rust-lang.org/t/idiomatic-way-to-refer-to-reference-or-value/46533/3 "2020-07-29T04:31:43Z")

</div>

It is more idiomatic to use `match` as an expression here instead of forward declaring `our_data`.

```rust
#[derive(Clone)]
struct Data {
    pub x: i32,
    pub y: i32,
}

struct Agent {
    q: i32,
    r: i32,
}

impl Agent {
    pub fn get_data(&self) -> Data {
        Data {
            x: self.q,
            y: self.r,
        }
    }

    fn do_stuff(agent: &Agent, data: Option<&Data>) {
        let our_data = match data {
            // Note: We need to clone the inner `&Data` because 
            // `Agent::get_data()` returns an owned `Data` and not a borrowed 
            // one (like the `data` parameter)
            Some(d) => d.clone(),
            None => agent.get_data(),
        };

        todo!()
    }
}

```

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

Your original code won't compile as-is because `Agent::get_data()` constructs a new (owned) `Data`, whereas the thing inside the `data` parameter is borrowed. I needed to make a copy of the `data` parameter's contents (`d.clone()`) so both branches have the same type.

---

<div class="post-metadata">

**Author:** ![L.F](https://avatars.discourse-cdn.com/v4/letter/l/43a26b/32.png) [@L.F](https://users.rust-lang.org/u/L.F)\
**Post date:** [July 29, 2020, 4:34am UTC](https://users.rust-lang.org/t/idiomatic-way-to-refer-to-reference-or-value/46533/4 "2020-07-29T04:34:59Z")

</div>

If you don't want to repeat the function call, you can extend the lifetime of the temporary by lifting it out of the `if` expression:

```rust
fn do_stuff(agent: &Agent, data: Option<&Data>) {
    let agent_data;
    let our_data = match data {
        None => {
            agent_data = agent.get_data();
            &agent_data
        }
        Some(data) => data,
    };
    do_other_things(our_data)
}

```

Rust's branch analysis is powerful enough in this case to figure it out.

---

<div class="post-metadata">

**Author:** ![L.F](https://avatars.discourse-cdn.com/v4/letter/l/43a26b/32.png) [@L.F](https://users.rust-lang.org/u/L.F)\
**Post date:** [July 29, 2020, 4:39am UTC](https://users.rust-lang.org/t/idiomatic-way-to-refer-to-reference-or-value/46533/5 "2020-07-29T04:39:50Z")

</div>

Additionally, if `Data` and `Agent` implement `Clone` (we won't actually clone it), you can use `Cow` to clarify the semantics:

```rust
fn do_stuff(agent: &Agent, data: Option<&Data>) {
    use std::borrow::Cow;

    let our_data = match data {
        None => Cow::Owned(agent.get_data()),
        Some(data) => Cow::Borrowed(data),
    };
    do_other_things(&our_data)
}

```

From the definition you showed, `Data` and `Agent` should have no trouble implementing `Clone`, I suppose.

---

<div class="post-metadata">

**Author:** ![diggyk](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/diggyk/32/16408_2.png) [@diggyk](https://users.rust-lang.org/u/diggyk)\
**Post date:** [July 29, 2020, 5:02am UTC](https://users.rust-lang.org/t/idiomatic-way-to-refer-to-reference-or-value/46533/6 "2020-07-29T05:02:24Z")

</div>

In the example, clone isn't bad. But in reality, it's a pretty big struct with lots of data in it, which is why I was hoping to avoid cloning.

---

<div class="post-metadata">

**Author:** ![diggyk](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/diggyk/32/16408_2.png) [@diggyk](https://users.rust-lang.org/u/diggyk)\
**Post date:** [July 29, 2020, 5:17am UTC](https://users.rust-lang.org/t/idiomatic-way-to-refer-to-reference-or-value/46533/7 "2020-07-29T05:17:57Z")

</div>

A quick question about this solution: under the hood, is the compiler still cloning the data or is it smartly just passing ownership of the memory? If this struct was something like 8 gigs of memory, am I going to have issues with perf?

---

<div class="post-metadata">

**Author:** ![L.F](https://avatars.discourse-cdn.com/v4/letter/l/43a26b/32.png) [@L.F](https://users.rust-lang.org/u/L.F)\
**Post date:** [July 29, 2020, 5:53am UTC](https://users.rust-lang.org/t/idiomatic-way-to-refer-to-reference-or-value/46533/8 "2020-07-29T05:53:38Z")

</div>

Assuming that the 8GiB of memory is stored on the heap (since it's probably gonna overflow the stack), and the `struct`s merely hold a pointer to it, no, there is no cloning going on.

---

<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:** [October 27, 2020, 5:53am UTC](https://users.rust-lang.org/t/idiomatic-way-to-refer-to-reference-or-value/46533/9 "2020-10-27T05:53:52Z")

</div>

Closed on October 27, 2020, 5:53am 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.
