Menu
  • HOME
  • TAGS

Why is variable scope dependent on the definition order?

rust,borrow-checker

Bindings are dropped in reverse order of declaration, i.e. the most recently declared thing is destroyed first. Specifically, in the code that doesn't work, the destructor of val runs before the destructor of v. Without careful consideration of what Vec<&str>::drop() does, this is not safe: It could for example try...

Borrow checker failing when using traits as type parameter

rust,borrow-checker

The problem here is that the borrow checker is forcing the lifetime of the &mut Trait reference to be the same as the whole GenericStruct. I believe this is because the reference is a type parameter of the struct itself. Since your struct has no fields that store the reference...

Match statement with explicit return of a borrowed reference

rust,borrow-checker

I am new to Rust myself too, but I believe I might have found the source of your problem. You can inspect the type signature of "get" function here. As you can see, "get" function returns a borrowed reference to the requested member of the vector (wrapped inside Option). My...

Storing mutable references and lifetimes

rust,lifetime,borrow-checker

The reason it works with immutable references is because those can be implicitly copied. When you switch to trying to return a &mut, then there would be two places that have that reference - the Vec and the caller of your function. This would introduce aliasing, and mutable aliases are...

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

rust,borrow-checker

The problem is that the Peekable iterator lives to the end of the function, but it holds a reference to the vector returned by get_m, which only lasts as long as the statement containing that call. There are actually a lot of things going on here, so let's take it...

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

rust,borrow-checker

I'm still in the everything is copied by value mindset, where it is perfectly legal to do self.color as that would get me a copy of Color. Apparently, I am wrong. I found some other questions about this same error on SO, but no solution to my issue. Anything...

Borrowed value does not live long enough when creating a Vec

rust,lifetime,borrow-checker

The problem comes from filestem_str. This is the signature: fn filestem_str<'a>(&'a self) -> Option<&'a str> This indicates that the method will return a borrowed reference to a string. The Path struct is the owner of the string. When you leave the method, there's nowhere left that owns the Path, so...

Unable to pipe to or from spawned child process more than once

process,command,pipe,rust,borrow-checker

As I guessed, read_to_end is waiting until all the input is done, which will never happen until the shell is closed. You can fix this by reading a set amount of data from the output. Here's an example where I removed all the nice error printing you had to show...

Changing a node in a tree in Rust

rust,borrow-checker

This code compiles: #[derive(Clone)] pub enum Node { Value(u32), Branch(u32, Box<Node>, Box<Node>), } fn main() { let root = Node::Branch(1, Box::new(Node::Value(2)), Box::new(Node::Value(3))); zero_node(&root, 2); } pub fn zero_node (tree: &Node, node_index: u8) -> Node { let mut new_tree = tree.clone(); fn zero_rec (node : &mut Node, node_count : u8, node_index...

Regex capture iterator method moves iterator

regex,iterator,rust,borrow-checker

I suspect that you're thinking of iter as being an abstract sequence of captures. It is more accurate to think of it as representing a position within an abstract sequence of captures. The basic thing any iterator knows to do is advance to the next item in a sequence; that...

Cannot borrow as immutable - String and len()

rust,immutability,mutability,borrow-checker

This is an unfortunate shortcoming of Rust borrow checking procedure. This essentially happens because result.truncate(result.len() - 2) is equivalent to String::truncate(&mut result, result.len() - 2) and here you can see that because arguments are computed in left-to-right order, result is indeed borrowed mutably before it is used in result.len(). I...

Is this kind of borrowing the “Rust way”?

rust,borrow-checker

Why does it need to borrow "process" at all?" Because you are using Option::as_mut. The signature looks like: fn as_mut<'r>(&'r mut self) -> Option<&'r mut T> This says that the lifetime of the return value is tied to the input. Additionally, it's a mutable reference, which you are only...

Modifying one attribute of a struct while iterating over another attribute

iterator,rust,borrow-checker

I think I have "solved" this problem using macros. If I use the following code, it works: use std::slice; struct S { a: Vec<i32>, b: Vec<i32> } impl S { fn a_push(&mut self, val: i32) { self.a.push(val); } } macro_rules! a_iter { ($x: expr) => { { $x.a.iter() } }...

How is a destructor call `fn drop(&mut self)` call inserted when the owning variable is immutable?

pointers,rust,ownership,borrow-checker

The owner of a variable gets to decide the mutability when the variable binding is created, it's not intrinsic to the value itself: fn main() { let x = vec![1, 2, 3]; let mut z = x; let y = &mut z; } You can think of dropping as happening...

Borrow checker on parent-child relation

rust,borrow-checker

and the mutable/immutable words in the error are not relevant I'm not sure why you think this. Mutability is very important in Rust! For example, while you are allowed multiple references to immutable data at the same time, you are only allowed to have a single reference to mutable...

Threaded calling of functions in a vector

multithreading,function,rust,borrow-checker

Updated question I meant "call them in their own thread" The easiest thing to do is avoid the Fn* traits, if possible. If you know that you are only using full functions, then it's straightforward: use std::thread; fn a() { println!("a"); } fn b() { println!("b"); } fn main() {...

How to use (unsafe) aliasing?

rust,strict-aliasing,borrow-checker

Your main function will have to be implemented using unsafe code in order to use raw pointers. Raw pointers allow you to bypass Rust's aliasing rules. You can then have two functions that act as safe façades for this unsafe implementation. unsafe fn foo(src: *const u8, dst: *mut u8, len:...

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

multithreading,rust,borrow-checker

No. But you might have the wrong idea: cloning an Arc is just incrementing a reference counter and making a copy of a pointer; it doesn't perform any allocation. (Edit: Of course, putting something in an Arc involves an allocation, but then, you're already allocating in order to construct the...

Can you control borrowing a struct vs borrowing a field?

rust,borrow-checker

Yes, you've guessed correctly - the error happens because when you have merge method accept &self, the compiler can't know at its call site that it uses only some fields - merge signature only tells it that the data it returns is somehow derived from self, but it doesn't tell...

Implementing a “cautious” take_while using Peekable

iterator,rust,traits,borrow-checker

The funny thing with by_ref() is that it returns a mutable reference to itself: pub trait IteratorExt: Iterator + Sized { fn by_ref(&mut self) -> &mut Self { self } } It works because the Iterator trait is implemented for the mutable pointer to Iterator type. Smart! impl<'a, I> Iterator...

Tree traversal in Rust vs Borrow Checker

data-structures,rust,borrow-checker

Here's a variant of your first approach, using recursion to avoid borrowing conflicts. The iterative equivalent fails to compile because Rust is too strict when dealing with mutable borrowed pointers to mutable values. impl Node { fn traverse_path<'p>(&mut self, mut path: &'p [Id]) -> (&mut Node, &'p [Id]) { //...

Passing self reference to method of owned object

rust,borrow-checker

Currently your Ball struct needs to know about the Field it's contained in to be able to update itself. This doesn't compile because the result would be cyclic references combined with mutation. You could make this work by using Cell or RefCell (the latter having a performance cost) but it...

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

rust,object-lifetime,borrow-checker

A raw design of the structs based on your requirements might look like this: struct AnotherObj<'a> { original: &'a Vec<i8>, // Let's agree on Vec<i8> as your "data" type. } struct Obj<'a> { original: Vec<i8>, // <-------------------+ processed: AnotherObj<'a>, // should point here --+ } However it's very tricky to...

Can't borrow File from &mut self (error msg: cannot move out of borrowed content)

rust,borrow-checker

self has type &mut Foo in print, that is, it is a borrowed mutable reference to a value of type Foo. Types in Rust move ownership by default, that is, taking something by-value will statically invalidate the source and stop the programmer from using it again (unless it is reinitialized)....

How to return a pointer to owned value that “does not live long enough”?

rust,borrow-checker

Here's why you can't return &node: fn create_node(&mut self) -> &Node { let index = self.nodes.len(); let node = Node { id: index }; println!("{}", &node as *const Node); self.nodes.push(node); println!("{}", &self.nodes[index] as *const Node); return &self.nodes[index]; } Here's a sample output: 0x7fffc36a3418 0x7f4c96c2d000 As you can see, &node and...