ref Keyword In Rust

June 23rd 2025

TIL about the ref keyword in rust.

As part of my twine project I wrote this pattern match:

let output_path = match args.output {
    Some(filename) => Self::generate_output_path(&filename),
    None => Self::generate_output_path(&uid.as_str()),
};

Ok(Twine { url, uid, args, file_url, output_path })

Which produces this error:

error[E0382]: use of partially moved value: `args`
  --> src/main.rs:89:30
   |
83 |             Some(filename) => Self::generate_output_path(&filename),
   |                  -------- value partially moved here
...
89 |         Ok(Twine { url, uid, args, file_url, output_path })
   |                              ^^^^ value used here after partial move
   |
   = note: partial move occurs because value has type `std::string::String`, which does not implement the `Copy` trait
help: borrow this binding in the pattern to avoid moving the value
   |
83 |             Some(ref filename) => Self::generate_output_path(&filename),
   |                  +++

As the compiler points out, the match moves the string it’s matching– presumeably into the scope of what I assume is an anonymous function. Adding the ref keyword tells the compiler that the match should borrow instead.

Using:

--snip--

Some(ref filename) => Self::generate_output_path(&filename),

--snip--

gets the job done just fine, and allows the struct creation because it can retain ownership of its intended members.