FAQ Database Discussion Community


Regex capture iterator method moves iterator

regex,iterator,rust,borrow-checker
I am processing simple strings of the format "1s:1d", "100:5000", etc with this regex: let retention_matcher = regex::Regex::new({r"^(\d+)([smhdy])?:(\d+)([smhdy])?$"}).unwrap(); I know this regex should only match once so I want to run the regex for captures and check the number of captures. let iter = retention_matcher.captures_iter(ts); let count = iter.count(); println!("iter.count():...

Match statement with explicit return of a borrowed reference

rust,borrow-checker
While taking a look at Rust I noticed a behavior I do not quite understand. I've got this code, which works as expected: fn get_or_create_foo(v: &mut Vec<String>) -> String { match v.get(0) { Some(x) => return x.clone(), None => () } println!("creating foo"); v.push("foo".to_string()); v.get(0).unwrap().clone() } fn main() { let...

Borrowed value does not live long enough when creating a Vec

rust,lifetime,borrow-checker
I try to list the file in a dir, and then copy the filename to my own Vec. I tried several solutions but it always ends up with a problem of not being able to create long enough living variables. I don't understand my mistake. fn getList(action_dir_path : &str) ->...

Threaded calling of functions in a vector

multithreading,function,rust,borrow-checker
I have an EventRegistry which people can use to register event listeners. It then calls the appropriate listeners when an event is broadcast. But, when I try to multithread it, it doesn't compile. How would I get this code working? use std::collections::HashMap; use std::thread; struct EventRegistry<'a> { event_listeners: HashMap<&'a str,...

Is this kind of borrowing the “Rust way”?

rust,borrow-checker
When I try to start another application, write some stuff on it's stdin and then wait for it so finish, my code looks something like this (old_io): let mut process = Command::new("example_app") .arg("test").spawn().ok().expect("Failed."); { let mut std = &mut process.stdin.as_mut().unwrap(); std.write_all(input_example); } let output = process.wait_with_output().ok().expect("Failed."); That's working, but I...

Implementing a “cautious” take_while using Peekable

iterator,rust,traits,borrow-checker
I'd like to use Peekable as the basis for a new cautious_take_while operation that acts like take_while from IteratorExt but without consuming the first failed item. (There's a side question of whether this is a good idea, and whether there are better ways to accomplish this goal in Rust --...

Understanding lifetimes (“help: consider using a `let` binding” — when I am)

rust,borrow-checker
In the following trivially short snippet, can someone explain my error and how to fix it? Any insight into the compiler error (which seems friendly but also totally non-applicable) would be a great help too. (Live example at http://is.gd/Vmi1fM.) Note: this question is clearly similar to Using a `let` binding...

How to use (unsafe) aliasing?

rust,strict-aliasing,borrow-checker
Rust has strict aliasing rules. But can I work around them if "I know what I'm doing"? I'm trying to convert to Rust a C function that performs a complicated operation by reading from input buffer and writing to a destination buffer, but it has a clever optimization that allows...

Struct that owns some data and a reference to the data [duplicate]

rust,object-lifetime,borrow-checker
This question already has an answer here: How to initialize struct fields which reference each other 1 answer Construction of an object allocates data needed for lifetime of that object, but also creates another object that needs to keep references to the data: pub fn new() -> Obj {...

Can you control borrowing a struct vs borrowing a field?

rust,borrow-checker
I'm working on a program involving a struct along these lines: struct App { data: Vec<u8>, overlay: Vec<(usize, Vec<u8>)>, sink: Sink, } In brief the data field holds some bytes and overlay is a series of byte sequences to be inserted at specific indices. The Sink type is unimportant except...

Storing mutable references and lifetimes

rust,lifetime,borrow-checker
I've now spent a number of fruitless hours trying to get this to work, but I'm afraid my only recourse now is to try and summarize my code and ask you all for help. The situation is, if I uncomment the two instances of mut in the following code, it...

Why is variable scope dependent on the definition order?

rust,borrow-checker
I have a basic (and probably stupid) ownership question. I am trying to create a vector of &str from String values wrapped inside Some(String). I am using an intermediate variable to store the extracted/unwrapped String and it seems I need to define this intermediary variable before the vector in order...

Passing self reference to method of owned object

rust,borrow-checker
Consider the following example: fn main() { let mut field = Field::new(Vector2d{x: 100, y: 100}); field.update(); } #[derive(Copy, Clone)] struct Vector2d { x: i32, y: i32, } struct Ball { radius: i32, position: Vector2d, velocity: Vector2d, } impl Ball { fn new(radius: i32, position: Vector2d, velocity: Vector2d) -> Ball {...

Cannot borrow as immutable - String and len()

rust,immutability,mutability,borrow-checker
let mut result = String::with_capacity(1000); result.push_str("things... "); result.push_str("stuff... "); result.truncate((result.len() - 4)); However, this is a compile error. Something to do with the borrow checker and possibly mutability. multipolygon.rs:63:21: 63:27 error: cannot borrow `result` as immutable because it is also borrowed as mutable multipolygon.rs:63 result.truncate((result.len() - 2)); ^~~~~~ multipolygon.rs:63:4: 63:10...

Get an enum field from a struct: cannot move out of borrowed content

rust,borrow-checker
I'm new to Rust and trying to wrap my head around the ownership/borrowing concept. Now I have reduced my code to this minimal code sample that gives a compile error. pub struct Display { color: Color, } pub enum Color { Blue = 0x1, Red = 0x4, } impl Display...

Borrow checker on parent-child relation

rust,borrow-checker
I have the code below producing the error message marked in its comments. I think I understand the message: I want to borrow parent two times: once for finding its child, and once as an argument to the child (and the mutable/immutable words in the error are not relevant). I...

Is it possible to share data with threads without any cloning?

multithreading,rust,borrow-checker
Often when I'm delegating work to threads I have a piece of data that will outlive all of the threads. An example would be numbers in the following example: use std::thread; fn main() { let numbers = vec![1, 2, 3]; let thread_a = thread::spawn(|| { println!("{}", numbers.len()); }); let thread_b...