I'm trying to print out a tree (it's a LinkedList right now, but that will be fixed):
use std::io;
use std::rc::Rc;
enum NodeKind {
Branch(Rc<Node>),
Leaf,
}
struct Node {
value: i32,
kind: NodeKind,
}
fn main() {
let leaf = Node { value: 10, kind: NodeKind::Leaf };
let branch = Node { value: 50, kind: NodeKind::Branch(Rc::new(leaf)) };
let root = Node { value: 100, kind: NodeKind::Branch(Rc::new(branch)) };
let mut current = root;
while true {
println!("{}", current.value);
match current.kind {
NodeKind::Branch(next) => {
current = *next;
}
NodeKind::Leaf => {
break;
}
}
}
let mut reader = io::stdin();
let buff = &mut String::new();
let read = reader.read_line(buff);
}
The compiler says:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:24:27
|
24 | current = *next;
| ^^^^^ cannot move out of borrowed content
I'm reading the value only, not changing anything. I'm assigning a value from a reference to another value, trying to dereference an Rc<T> value and store it in a local mut variable.
maybe something like this may work:
while true {
println!("{}", current.value);
match ¤t.kind {
&NodeKind::Branch(next) => {
current = next;
}
&NodeKind::Leaf => {
break;
}
}
}
or maybe
let mut current = &Rc::new(root);
while true {
println!("{}", current.value);
match current.kind {
NodeKind::Branch(next) => {
current = &next;
}
NodeKind::Leaf => {
break;
}
}
}
but I get the same error plus 'next' does not live long enough
There is no need to clone here, it is absolutely possible to do what you want to achieve with references:
use std::rc::Rc;
enum NodeKind {
Branch(Rc<Node>),
Leaf,
}
struct Node {
value: i32,
kind: NodeKind,
}
fn main() {
let leaf = Node { value: 10, kind: NodeKind::Leaf };
let branch = Node { value: 50, kind: NodeKind::Branch(Rc::new(leaf)) };
let root = Node { value: 100, kind: NodeKind::Branch(Rc::new(branch)) };
let mut current = &root;
loop {
println!("{}", current.value);
match current.kind {
NodeKind::Branch(ref next) => {
current = &**next;
}
NodeKind::Leaf => break,
}
}
}
The only important changes from your code is that the pattern in the match is ref next and current is of type &Node.
ref patterns bind their variables by reference, that is, next has type &Rc<Node>. To get &Node from it, you need to dereference it two times to get Node and then reference again to get &Node. Due to Deref coercions, it is also possible to write current = &next, and the compiler will insert an appropriate number of *s for you automatically.
I also changed from while (true) to loop because it is more idiomatic and it helps the compiler to reason about your code.
All traversals of tree-like structures are done like this in Rust. ref patterns allow not to move out of variables, which is absolutely necessary when you only need to read data. You can find more about patterns and how they interact with ownership and borrowing here.
The error is displayed because by default match will perform a move.
After a value is moved (i.e. wasn't taken by reference or method that takes self was called) subsequent calls fail. You'll probably need to clone, which is a property both of your struct and enum lack. Once you add those (#[derive(Clone)) and change current = *next; into current = (*next).clone();, your program will work again!
use std::io;
use std::rc::Rc;
#[derive(Clone)]
enum NodeKind {
Branch(Rc<Node>),
Leaf,
}
#[derive(Clone)]
struct Node {
value: i32,
kind: NodeKind,
}
fn main() {
let leaf = Node { value: 10, kind: NodeKind::Leaf };
let branch = Node { value: 50, kind: NodeKind::Branch(std::rc::Rc::new(leaf)) };
let root = Node { value: 100, kind: NodeKind::Branch(std::rc::Rc::new(branch)) };
let mut current = root;
while true {
println!("{}", current.value);
match current.kind {
NodeKind::Branch(next) => {
current = (*next).clone();
}
NodeKind::Leaf => {
break;
}
}
}
let reader = io::stdin();
let buff = &mut String::new();
let read = reader.read_line(buff);
}
Playground
If you let mut current = &root then you can avoid clone() as per Vladimir's response below (playpen of Vladimir's version).
I can't figure out the issue with 1) yet, but I did find an answer for 2).
At the top, you need to use:
use std::rc::Rc;
instead of
use std::rc;
Related
I have a structure like
struct Node {
pub id: String,
pub dis: String,
pub parent: Option<NodeRefNodeRefWeak>,
pub children: Vec<NodeRef>,
}
pub type NodeRef = Rc<RefCell<Node>>;
pub type NodeRefNodeRefWeak = Weak<RefCell<Node>>;
I also have a start of a function that can iterate this structure to
pull out a match on a node id but it has issues.
What I would like is for this function to return the parent node of the whole tree with ONLY the branches that have a match somewhere on the branch.
Children past the search node can be removed.
Ie a function that filters all other nodes out of the tree.
For example with my rust playground link I would like it to return
level0_node_#1 (level0_node_#1)
level1_node_4 (level1_node_4)
level2_node_4_3 (level2_node_4_3)
level3_node_4_3_2 (level3_node_4_3_2)
However, using the recursive approach as below causes real issue with already borrowed errors when trying to remove branches etc.
Is there a way to achieve this filter function?
I have a test in the Rust playground.
fn tree_filter_node_objects<F>(node: &NodeRef, f: F) -> Vec<NodeRef>
where F: Fn(&str) -> bool + Copy {
let mut filtered_nodes: Vec<NodeRef> = vec![];
let mut borrow = node.borrow_mut();
if f(&borrow.id) {
filtered_nodes.push(node.clone());
}
for n in borrow.children.iter() {
let children_filtered = tree_filter_node_objects(n, f);
for c in children_filtered.iter() {
filtered_nodes.push(c.clone());
}
}
filtered_nodes
}
In the end I used this iterative approach.
pub fn tree_filter_node_dfs<F>(root: &NodeRef, f: F) -> Vec<NodeRef>
where F: Fn(&BmosHaystackObject) -> bool + Copy {
let mut filtered_nodes: Vec<NodeRef> = vec![];
let mut cur_node: Option<NodeRef> = Some(root.clone());
let mut last_visited_child: Option<NodeRef> = None;
let mut next_child: Option<NodeRef>;
let mut run_visit: bool = true;
while cur_node.is_some() {
if run_visit {
let n = cur_node.as_ref().unwrap();
if f(&n.borrow().object) {
}
}
if last_visited_child.is_none() {
let children = cur_node.as_ref().unwrap().borrow().children.clone();
if children.len() > 0 {
next_child = Some(children[0].clone());
}
else {
next_child = None;
}
}
else {
next_child = tree_filter_node_get_next_sibling(last_visited_child.as_ref().unwrap());
}
if next_child.is_some() {
last_visited_child = None;
cur_node = next_child;
run_visit = true;
}
else {
last_visited_child = cur_node;
cur_node = tree_node_parent_node(&last_visited_child.clone().unwrap().clone());
run_visit = false;
}
}
filtered_nodes
}
I want to implement some basic methods for Trie.
use std::collections::HashMap;
#[derive(Debug)]
struct TrieNode {
chs: HashMap<char, TrieNode>,
value: Option<i32>,
}
#[derive(Debug)]
struct Trie {
root: TrieNode,
}
impl Trie {
fn new() -> Trie {
Trie {
root: TrieNode {
chs: HashMap::new(),
value: None,
},
}
}
fn add_string(&mut self, string: String, value: i32) {
let mut current_node = &mut self.root;
for c in string.chars() {
current_node = current_node.chs.entry(c).or_insert(TrieNode {
chs: HashMap::new(),
value: None,
});
}
current_node.value = Some(value);
}
fn delete(&mut self, key: &String) -> Option<i32> {
if key.is_empty() {
// if key is empty, no need to delete
return None;
}
let mut current_node = &mut self.root;
for (ind, ch) in key.chars().enumerate() {
match current_node.chs.get_mut(&ch) {
Some(node) => {
if ind < key.len() - 1 {
current_node = node;
}
}
None => return None,
}
}
// here current_node is actually the previous node of the deleted node
let temp = current_node.chs.remove(&key.chars().last().unwrap());
match temp {
Some(node) => node.value,
None => None,
}
}
}
The method delete is to remove a key (from a Trie) and returns the value corresponding to that key. However, I got the following error.
error[E0499]: cannot borrow `current_node.chs` as mutable more than once at a time
--> src/main.rs:118:19
|
118 | match current_node.chs.get_mut(&ch) {
| ^^^^^^^^^^^^^^^^ mutable borrow starts here in previous iteration of loop
I'm not exactly sure where the borrow checker is getting tripped up, but you can fix it by hoisting the if check:
let mut current_node = &mut self.root;
for (ind, ch) in key.chars().enumerate() {
if ind < key.len() - 1 {
match current_node.chs.get_mut(&ch) {
Some(node) => {
current_node = node;
}
None => return None,
}
}
}
It skips over even checking if the leaf node exists, but your remove( match already covers that case.
Also, your ind < key.len() - 1 check assumes that the last character is ascii. It may be true for your use case, but if not you can use this answer to iterate until the penultimate character instead.
As the error message explains, you cannot borrow a value (current_node.chs) as mutable more than once at a time.
One solution is to derive the Clone trait for TrieNode. Clone is a common trait for the ability to explicitly duplicate an object:
#[derive(Debug, Clone)]
struct TrieNode {
chs: HashMap<char, TrieNode>,
value: Option<i32>,
}
Now instead of borrowing self.root, you can clone it:
fn delete(&mut self, key: &String) -> Option<i32> {
if key.is_empty() {
return None
}
// clone `self.root`
let mut current_node = self.root.clone();
for (ind, ch) in key.chars().enumerate() {
match current_node.chs.get_mut(&ch) {
Some(node) => {
if ind < key.len() - 1 {
// clone `node`
current_node = node.clone();
}
// ...
If performance is an issue, then cloning is probably not the best idea. However, it is still an option and may or may not suit your use case.
I wish that enums in Rust can be used like Haskell's productive type. I want to
access a field's value directly
assign a field's value directly or make a clone with the changing value.
Directly means that not using too long pattern matching code, but just could access like let a_size = a.size.
In Haskell:
data TypeAB = A {size::Int, name::String} | B {size::Int, switch::Bool} deriving Show
main = do
let a = A 1 "abc"
let b = B 1 True
print (size a) -- could access a field's value directly
print (name a) -- could access a field's value directly
print (switch b) -- could access a field's value directly
let aa = a{size=2} -- could make a clone directly with the changing value
print aa
I tried two styles of Rust enum definition like
Style A:
#[derive(Debug)]
enum EntryType {
A(TypeA),
B(TypeB),
}
#[derive(Debug)]
struct TypeA {
size: u32,
name: String,
}
#[derive(Debug)]
struct TypeB {
size: u32,
switch: bool,
}
fn main() {
let mut ta = TypeA {
size: 3,
name: "TAB".to_string(),
};
println!("{:?}", &ta);
ta.size = 2;
ta.name = "TCD".to_string();
println!("{:?}", &ta);
let mut ea = EntryType::A(TypeA {
size: 1,
name: "abc".to_string(),
});
let mut eb = EntryType::B(TypeB {
size: 1,
switch: true,
});
let vec_ab = vec![&ea, &eb];
println!("{:?}", &ea);
println!("{:?}", &eb);
println!("{:?}", &vec_ab);
// Want to do like `ta.size = 2` for ea
// Want to do like `ta.name = "bcd".to_string()` for ea
// Want to do like `tb.switch = false` for eb
// ????
println!("{:?}", &ea);
println!("{:?}", &eb);
println!("{:?}", &vec_ab);
}
Style B:
#[derive(Debug)]
enum TypeCD {
TypeC { size: u32, name: String },
TypeD { size: u32, switch: bool },
}
fn main() {
// NOTE: Rust requires representative struct name before each constructor
// TODO: Check constructor name can be duplicated
let mut c = TypeCD::TypeC {
size: 1,
name: "abc".to_string(),
};
let mut d = TypeCD::TypeD {
size: 1,
switch: true,
};
let vec_cd = vec![&c, &d];
println!("{:?}", &c);
println!("{:?}", &d);
println!("{:?}", &vec_cd);
// Can't access a field's value like
// let c_size = c.size
let c_size = c.size; // [ERROR]: No field `size` on `TypeCD`
let c_name = c.name; // [ERROR]: No field `name` on `TypeCD`
let d_switch = d.switch; // [ERROR]: No field `switch` on `TypeCD`
// Can't change a field's value like
// c.size = 2;
// c.name = "cde".to_string();
// d.switch = false;
println!("{:?}", &c);
println!("{:?}", &d);
println!("{:?}", &vec_cd);
}
I couldn't access/assign values directly in any style. Do I have to implement functions or a trait just to access a field's value? Is there some way of deriving things to help this situation?
What about style C:
#[derive(Debug)]
enum Color {
Green { name: String },
Blue { switch: bool },
}
#[derive(Debug)]
struct Something {
size: u32,
color: Color,
}
fn main() {
let c = Something {
size: 1,
color: Color::Green {
name: "green".to_string(),
},
};
let d = Something {
size: 2,
color: Color::Blue { switch: true },
};
let vec_cd = vec![&c, &d];
println!("{:?}", &c);
println!("{:?}", &d);
println!("{:?}", &vec_cd);
let _ = c.size;
}
If all variant have something in common, why separate them?
Of course, I need to access not common field too.
This would imply that Rust should define what to do when the actual type at runtime doesn't contain the field you required. So, I don't think Rust would add this one day.
You could do it yourself. It will require some lines of code, but that matches the behavior of your Haskell code. However, I don't think this is the best thing to do. Haskell is Haskell, I think you should code in Rust and not try to code Haskell by using Rust. That a general rule, some feature of Rust come directly from Haskell, but what you want here is very odd in my opinion for Rust code.
#[derive(Debug)]
enum Something {
A { size: u32, name: String },
B { size: u32, switch: bool },
}
impl Something {
fn size(&self) -> u32 {
match self {
Something::A { size, .. } => *size,
Something::B { size, .. } => *size,
}
}
fn name(&self) -> &String {
match self {
Something::A { name, .. } => name,
Something::B { .. } => panic!("Something::B doesn't have name field"),
}
}
fn switch(&self) -> bool {
match self {
Something::A { .. } => panic!("Something::A doesn't have switch field"),
Something::B { switch, .. } => *switch,
}
}
fn new_size(&self, size: u32) -> Something {
match self {
Something::A { name, .. } => Something::A {
size,
name: name.clone(),
},
Something::B { switch, .. } => Something::B {
size,
switch: *switch,
},
}
}
// etc...
}
fn main() {
let a = Something::A {
size: 1,
name: "Rust is not haskell".to_string(),
};
println!("{:?}", a.size());
println!("{:?}", a.name());
let b = Something::B {
size: 1,
switch: true,
};
println!("{:?}", b.switch());
let aa = a.new_size(2);
println!("{:?}", aa);
}
I think there is currently no built-in way of accessing size directly on the enum type. Until then, enum_dispatch or a macro-based solution may help you.
I am new to Rust and want to write linked list in Rust to have fun. I am confused about how to delete a node in the linked list. Here is my simple code.
#[derive(Debug)]
struct Node{
v: usize,
next: Option<Box<Node>>,
}
struct LinkedList {
head: Option<Box<Node>>,
}
impl LinkedList {
fn remove(&mut self, v: usize) -> Option<usize> {
let mut current_node: &mut Option<Box<Node>> = &mut self.head;
loop {
match current_node {
None => break,
Some(node) => {
if node.v == v {
// current_node = what?
// ???????????????
break;
} else {
current_node = &mut node.next;
}
},
};
}
match current_node.take().map(|x| *x) {
Some(node) => {
*current_node = node.next;
return Some(node.v)
},
None => None,
}
}
}
And here is the rust playground. I am using the nightly version and edition = 2018. In the loop, I try to find the node whose next node contains the value that I search for. However, I am confused about what to write in the ?? position.
There isn't really code that can go in that space to fix it; you'll need to make some bigger changes.
One of the problems is that you have mutably borrowed the current node in current_node, but then need to mutate it while that reference still exists.
Making use of non-lexical lifetimes in Edition 2018, you can do:
impl LinkedList {
fn remove(&mut self, v: usize) -> Option<usize> {
let mut current = &mut self.head;
loop {
match current {
None => return None,
Some(node) if node.v == v => {
*current = node.next.take();
return Some(v);
},
Some(node) => {
current = &mut node.next;
}
}
}
}
}
Somehow, using the match guard if node.v == v to make two match arms, instead of using an if condition inside one match arm, lets the borrower checker deduce that this is safe. I'm not sure why the if statement inside the match arm isn't allowed - there are some of the opinion that this could be a bug.
inspire by above answer, my solution is:
fn removeKFromList(mut head: ListNode<i32>, k: i32) -> ListNode<i32> {
if head.is_none() {
return None;
}
let mut current = &mut head;
loop {
match current {
None => break,
Some(node) if node.value == k => {
*current = node.next.take();
},
Some(node) => {
current = &mut node.next;
}
}
}
return head;
}
Here is solution, if you have generic List, which accepts arbitrary type of content type T and returns deleted content to caller:
impl<T> LinkedList<T> {
pub fn remove_f<F: Fn(&T) -> bool>(&mut self, comparator: F) -> Option<T> {
let mut curr_link = &mut self.head;
loop {
match curr_link {
None => return None,
Some(node_ref) if comparator(&node_ref.elem) => {
let node = curr_link.take().unwrap();
*curr_link = node.next;
return Some(node.elem);
},
Some(node) => curr_link = &mut node.next,
};
}
}
}
Use example, assume T = &str and list contains element with value "1" and no element with value "smth":
assert_eq!(list.remove_f(|node| "1".eq(node.deref())), Some("1"));
assert_eq!(list.remove_f(|node| "smth".eq(node.deref())), None);
I am fairly new to Rust and want to implement an AVL-Tree.
I am using the following enum to represent my tree:
enum AvlTree<T> {
Leaf,
Node {
left: Box<AvlTree<T>>,
right: Box<AvlTree<T>>,
value: T
}
}
When implementing one of the balance-functions, I'm facing some problems with ownership and borrowing.
I am trying to write a function, which takes an AvlTree<T> and returns another AvlTree<T>. My first attempt was something like this:
fn balance_ll(tree: AvlTree<T>) -> AvlTree<T> {
if let AvlTree::Node {left: t, right: u, value: v} = tree {
if let AvlTree::Node {left: ref tl, right: ref ul, value: ref vl} = *t {
AvlTree::Leaf // Return a new AvlTree here
} else {
tree
}
} else {
tree
}
}
Even with this minimal example, the compiler is returning an error:
error[E0382]: use of partially moved value: `tree`
--> avl.rs:67:17
|
63 | if let AvlTree::Node {left: t, right: u, value: v} = tree {
| - value moved here
...
67 | tree
| ^^^^ value used here after move
|
= note: move occurs because `(tree:AvlTree::Node).left` has type `std::boxed::Box<AvlTree<T>>`, which does not implement the `Copy` trait
I think, I'm understanding the error message correctly, in that destructuring the AvlTree::Node will take away the ownership of the tree example. How can I prevent this from happening? I already tried various things and (de-)referencing the tree-variable only to face more errors.
Additionally, I want to use some of the extracted values like u, tl and vl in the new struct. Is this possible and could you maybe provide a minimal example doing exactly that? I don't need access to the old tree after executing the function.
I think, I'm understanding the error message correctly, in that destructuring the AvlTree::Node will take away the ownership of the tree example.
Yes. If you still need to be able to use tree afterwards, you will either need to make a copy of it:
#[derive(Clone)]
enum AvlTree<T> {...}
fn balance_ll<T: Clone>(tree: AvlTree<T>) -> AvlTree<T> {
let copy = tree.clone();
if let AvlTree::Node { left: t, right: u, value: v } = tree {
if let AvlTree::Node { left: ref tl, right: ref ul, value: ref vl } = *t {
AvlTree::Leaf // Return a new AvlTree here
} else {
copy
}
} else {
tree
}
}
or use a helper function that quickly releases its ownership - but I don't think it is possible without box patterns:
#![feature(box_patterns)]
impl<T> AvlTree<T> {
fn is_left_node(&self) -> bool {
if let &AvlTree::Node { left: ref t, right: ref u, value: ref v } = self {
if let &box AvlTree::Node { left: ref tl, right: ref ul, value: ref vl } = t {
true
} else {
false
}
} else {
false
}
}
}
fn balance_ll<T>(tree: AvlTree<T>) -> AvlTree<T> {
if tree.is_left_node() {
AvlTree::Leaf
} else {
tree
}
}
Since you possibly want to use the destructured values you will probably prefer the clone variant, but maybe the other one will give you some extra ideas.