Reference "returned" by ref pattern

⚓ Rust    📅 2025-09-08    👤 surdeus    👁️ 3      

surdeus

Hei!
I need to use a default value in case the optional inputs to my function are not provided.
I came up with this snippet, but it feels a bit magical, especially given the use of ref.

const DEFAULT_VALUES: &[i32] = &[1, 2, 3];

fn magic(inputs: Option<Vec<i32>>) {
    let values = match inputs {
        Some(ref vals) => vals,
        None => DEFAULT_VALUES,
    };

    // data processing...
}

I guess my question is why does that snippet work, but if instead I use Some(vals) => &vals it doesn't? And also is there a better way to achieve what I'm trying to do?

3 posts - 3 participants

Read full topic

🏷️ Rust_feed