borrowing

How to make mutable pointer to field of node of tree and mutate it? [duplicate]

空扰寡人 提交于 2019-12-31 04:52:27
问题 This question already has answers here : Cannot obtain a mutable reference when iterating a recursive structure: cannot borrow as mutable more than once at a time (4 answers) Closed last year . I want to find some node in the tree and I need a pointer to the container of nodes: &mut Vec<Node> struct Node { c: Vec<Node>, v: i32, } impl Node { pub fn new(u: i32, n: Node) -> Node { let mut no = Node { c: Vec::new(), v: u, }; no.c.push(n); no } } fn main() { let mut a = Node::new(1, Node::new(2,

What disaster does the compiler prevent by disallowing assigning to a borrowed value?

£可爱£侵袭症+ 提交于 2019-12-24 16:50:48
问题 An example from Programming in Rust (PDF): #[derive(Debug)] enum IntOrString { I(isize), S(String), } fn corrupt_enum() { let mut s = IntOrString::S(String::new()); match s { IntOrString::I(_) => (), IntOrString::S(ref p) => { s = IntOrString::I(0xdeadbeef); // Now p is a &String, pointing at memory // that is an int of our choosing! } } } corrupt_enum(); The compiler does not allow this: error[E0506]: cannot assign to `s` because it is borrowed --> src/main.rs:13:17 | 12 | IntOrString::S(ref

Pass self reference to contained object's function

情到浓时终转凉″ 提交于 2019-12-22 11:31:55
问题 I'm trying to grok Rust's ownership model. I'm trying to pass a reference to a containing object when calling a function on a struct. Here's my struct: pub struct Player {} impl Player { pub fn receive(self, app: &App) { } } As you can see, receive expects a reference to an App object. pub struct App { pub player: Player, } impl App { pub fn sender(self) { // how to call player.test() and pass self as a reference? self.player.receive(&self); } } The above code gives me "use of partially moved

Why does cloning data inside a closure not prevent the error “closure may outlive the current function”?

会有一股神秘感。 提交于 2019-12-20 02:15:08
问题 I built a GTK application with gtk-rs. When I build the main window, I want to use some dynamic parameters such as window height. I created a struct which contains all such settings and want to use this as an input parameter for the function building the UI: fn main() { let application = gtk::Application::new(Some("id"), Default::default()) .expect("Initialization failed..."); let config = Config {width: 100., height: 100.}; application.connect_activate(|app| { build_ui(app, config.clone());

Value does not live long enough

好久不见. 提交于 2019-12-19 14:55:28
问题 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: &'static str, } impl Formater { pub fn new(layout: &'static str) -> Formater { let regex = Regex::new(r"%\{([a-z]+)(?::(.*?[^\\]))?\}").unwrap(); let b = regex.replace_all(layout, "{}"); return Formater { layout: &b, }; } } The error: error: `b` does

Unable to return a vector of string slices: borrowed value does not live long enough

风格不统一 提交于 2019-12-19 10:25:23
问题 I'm new to Rust and I'm having some trouble with the borrow checker. I don't understand why this code won't compile. Sorry if this is close to a previously answered question but I can't seem to find a solution in the other questions I've looked at. I understand the similarity to Return local String as a slice (&str) but in that case it is just one string being returned and not enough for me to reason with my code in which I am trying to return a vector. From what I understand, I am trying to

How to copy instead of borrow an i64 into a closure in Rust?

Deadly 提交于 2019-12-18 07:19:26
问题 I have the following minimal example of my code: fn main() { let names : Vec<Vec<String>> = vec![ vec!["Foo1".to_string(), "Foo2".to_string()], vec!["Bar1".to_string(), "Bar2".to_string()] ]; let ids : Vec<i64> = vec![10, 20]; names.iter().enumerate().flat_map(|(i,v)| { let id : i64 = ids[i]; v.iter().map(|n| (n.clone(), id) ) }); } Now, when I compile that with rustc I get the following error message: error[E0597]: `id` does not live long enough --> main.rs:12:16 | 11 | v.iter().map(|n| | --

How can I mutate other elements of a HashMap when using the entry pattern?

删除回忆录丶 提交于 2019-12-17 06:57:05
问题 I'd like to use a HashMap to cache an expensive computation that's dependent on other entries in the map. The entry pattern only provides a mutable reference to the matched value, but not to the rest of the HashMap . I'd really appreciate feedback on a better way to solve this (incorrect) toy example: use std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; fn compute(cache: &mut HashMap<u32, u32>, input: u32) -> u32 { match cache.entry(input) { Vacant(entry)

Cyclic reference of RefCell borrows in traversal

余生颓废 提交于 2019-12-13 16:07:30
问题 I'm learning Rust and tried coding a doubly-linked list. However, I'm stuck already at a typical iterative traversal implementation. I'm getting the impression that the borrow checker / drop checker is too strict and cannot infer the correct lifetime for the borrow when it crosses the function boundary from RefCell . I need to repeatedly set a variable binding ( curr in this case) to the borrow of its current contents: use std::cell::RefCell; use std::rc::Rc; pub struct LinkedList<T> { head:

Passing Vec<String> as IntoIterator<&'a str>

和自甴很熟 提交于 2019-12-12 11:31:05
问题 I have a function that is supposed to pick random words from a list of words: pub fn random_words<'a, I, R>(rng: &mut R, n: usize, words: I) -> Vec<&'a str> where I: IntoIterator<Item = &'a str>, R: rand::Rng, { rand::sample(rng, words.into_iter(), n) } Presumably that's a reasonable signature: Since I don't actually need the string itself in the function, working on references is more efficient than taking a full String . How do I elegantly and efficiently pass a Vec<String> with words that