Why can’t I reuse a &mut reference after passing it to a function that accepts a generic type?

Normally, when you pass a mutable reference to a function, the compiler implicitly performs a reborrow. This produces a new borrow with a shorter lifetime. When the parameter is generic (and is not of the form &mut T), the compiler doesn’t do this reborrowing automatically1. However, you can do it manually by dereferencing your existing … Read more

How to use a struct’s member as its own key when inserting the struct into a map without duplicating it?

It’s not going to work with plain references: let item = StructThatContainsString { id: “Some Key”.to_string(), other_data: 0, } ms.insert(&item.id, item); item is moved into the map, so there can’t be any pending borrows/references. Also, methods like get_mut() would become dangerous or impossible, as it would let you modify the item that has an outstanding … Read more

How to use struct self in member method closure

Split your data and methods into smaller components, then you can take disjoint borrows to various components on self: fn fetch_access_token(_base_url: &str) -> String { String::new() } fn get_env_url() -> String { String::new() } #[derive(Default)] struct BaseUrl(Option<String>); impl BaseUrl { fn get(&mut self) -> &str { self.0.get_or_insert_with(|| get_env_url()) } } #[derive(Default)] struct App { base_url: … Read more