home
NOTE: Under Construction - I'm in the middle of upgrading my site and lots of stuff is kinda broken. Please forgive the mess.

Create A New Copy Of An Object From A Reference In Rust

This took me some time (and a call for help) to figure out.

I've got a config I want to pass as a reference to lower functions. One of those needs to change a value.

Doing this straight-forward let mut config2 = config.clone(); does what I need.

April 2024
Code
#[derive(Debug, Clone)]
struct Config {
  item: String,
}

fn main() {
  let config = Config { 
    item: "alfa".to_string(),
  };
  do_something2(&config);
}

fn do_something1(config: &Config) {
  dbg!(&config.item);
}

fn do_something2(config: &Config) {
  let mut config2 = config.clone();
  config2.item = "bravo".to_string();
  do_something3(&config2);
  do_something1(&config);
}

fn do_something3(config: &Config) {
  dbg!(&config.item);
}
Results
[_active_nvim_run:25:3] &config.item = "bravo"
[_active_nvim_run:14:3] &config.item = "alfa"
═══ § ═══

Endnotes

  • The first time I tried this I was doing `*config.clone()` which doesn't work. It gives an error: error[E0614]: type 'Config' cannot be dereferenced