Questions tagged [borrowing]

Borrowing is a key concept in Rust: a borrowing object is usable by the borrower but its ownership is not transferred. In other languages, an equivalent is "taking by reference".

In Rust, one can mutably borrow an object once, or immutably borrow it multiple time, but one cannot do both.

You can read more about borrowing in the corresponding Rust book chapter.

322 questions
44
votes
3 answers

How to accept &str, String and &String in a single function?

I want to write a single function, that accepts a &str, a String and a borrowed &String. I've written the following 2 functions: fn accept_str_and_ref_string(value: &str) { println!("value: {}", value); } fn accept_str_and_string
Ringo Leese
  • 675
  • 1
  • 5
  • 6
40
votes
1 answer

Value does not live long enough

I don't completely understand lifetimes, but I think b's lifetime will end before self's. So, how to edit this code? Do I copy something in memory? If I make a new instance, this lifetime must adhere to this case. pub struct Formater { layout:…
彭灵俊
  • 403
  • 1
  • 4
  • 5
29
votes
2 answers

Why is "&&" being used in closure arguments?

I have two questions regarding this example: let a = [1, 2, 3]; assert_eq!(a.iter().find(|&&x| x == 2), Some(&2)); assert_eq!(a.iter().find(|&&x| x == 5), None); Why is &&x used in the closure arguments rather than just x? I understand that & is…
Sajuuk
  • 2,667
  • 3
  • 22
  • 34
27
votes
4 answers

Cannot obtain a mutable reference when iterating a recursive structure: cannot borrow as mutable more than once at a time

I'm trying to navigate a recursive data structure iteratively in order to insert elements at a certain position. To my limited understanding, this means taking a mutable reference to the root of the structure and successively replacing it by a…
Fabian Knorr
  • 3,134
  • 3
  • 20
  • 32
24
votes
1 answer

How to fix String field does not implement `Copy`?

I am building a simple command-line todo app in Rust. If I don't implement the copy trait I get this error: "move occurs because 'todo' has type 'todo::Todo', which does not implement the 'Copy' trait". When I try to implement the Copy trait for my…
Henry Boisdequin
  • 325
  • 1
  • 3
  • 9
22
votes
2 answers

How do I convert a HashSet of Strings into a Vector?

I'm trying to convert a HashSet into a sorted vector that can then be joined with commas: use std::collections::HashSet; fn main() { let mut hs = HashSet::::new(); hs.insert(String::from("fee")); …
Ralph
  • 31,584
  • 38
  • 145
  • 282
22
votes
4 answers

Cannot infer an appropriate lifetime for a closure that returns a reference

Considering the following code: fn foo<'a, T: 'a>(t: T) -> Box &'a T + 'a> { Box::new(move || &t) } What I expect: The type T has lifetime 'a. The value t live as long as T. t moves to the closure, so the closure live as long as t The…
xardas
  • 355
  • 1
  • 6
21
votes
2 answers

Why Rust prevents from multiple mutable references?

Like in the topic, why Rust prevents from multiple mutable references? I have read chapter in rust-book, and I understand that when we have multi-threaded code we are secured from data races but let's look at this code: fn main() { let mut x1 =…
mikeProgrammer
  • 427
  • 4
  • 10
21
votes
1 answer

When should I use a reference instead of transferring ownership?

From the Rust book's chapter on ownership, non-copyable values can be passed to functions by either transferring ownership or by using a mutable or immutable reference. When you transfer ownership of a value, it can't be used in the original…
MaiaVictor
  • 51,090
  • 44
  • 144
  • 286
16
votes
3 answers

Dereferencing strings and HashMaps in Rust

I'm trying to understand how HashMaps work in Rust and I have come up with this example. use std::collections::HashMap; fn main() { let mut roman2number: HashMap<&'static str, i32> = HashMap::new(); roman2number.insert("X", 10); …
skanur
  • 175
  • 2
  • 8
14
votes
1 answer

Cannot borrow in a Rc as mutable

First of all I'm new with Rust :-) The problem: I want to create a module called RestServer that contain the methods ( actix-web ) to add routes and start the server. struct Route { url: String, request: String, handler: Box
Andrea Mucci
  • 747
  • 2
  • 9
  • 25
13
votes
2 answers

How to decide when function input params should be references or not?

When writing a function how does one decide whether to make input parameters referenced or consumed? For example, should I do this? fn foo(val: Bar) -> bool { check(val) } // version 1 Or use referenced param instead? fn foo(val: &Bar) -> bool {…
prior
  • 339
  • 4
  • 10
13
votes
1 answer

In what scenarios are APIs that don't borrow preferred?

Rust has the concepts of ownership and borrowing. If a function doesn't borrow its parameter as a reference, the arguments to that function are moved and will be deallocated once they go out of scope. Take this function: fn build_user(email: String,…
Pascal Precht
  • 8,803
  • 7
  • 41
  • 53
11
votes
2 answers

Why is iterating over a collection via `for` loop considered a "move" in Rust?

I have the below Rust program. fn main() { let v = vec![100, 32, 57]; for i in v { println!("{}", i); } println!("{:?}", v); } When I run it, I get: error[E0382]: borrow of moved value: `v` --> src\main.rs:7:22 | 2 | …
Just a learner
  • 26,690
  • 50
  • 155
  • 234
11
votes
1 answer

How can I obtain an &A reference from a Rc>?

I have design issue that I would like solve with safe Rust that I haven't been able to find a viable solution. I can't use a RefCell because you can't get a & reference to the data, only Ref / RefMut. Here is a simplified example with irrelevant…
Jake
  • 245
  • 2
  • 10
1
2 3
21 22