Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

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 [TODO: Code shorthand span ] does what I need.

rust
#[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 start

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