Posts

Showing posts with the label rust

How do I assert an enum is a specific variant if I don't care about its fields?

How do I assert an enum is a specific variant if I don't care about its fields? I'd like to check enums with fields in tests while ignoring the actual value of the fields for now. Consider the following example: enum MyEnum { WithoutFields, WithFields { field: String }, } fn return_with_fields() -> MyEnum { MyEnum::WithFields { field: "some string".into(), } } #[cfg(test)] mod tests { use super::*; #[test] fn example() { assert_eq!(return_with_fields(), MyEnum::WithFields {..}); } } playground I'd like to use assert_eq! here, but the compiler tells me: assert_eq! error: expected expression, found `}` --> src/lib.rs:18:64 | 18 | assert_eq!(return_with_fields(), MyEnum::WithFields {..}); | ^ expected expression This is similar to Why do I get an error when pattern matching a struct-like enum variant with fields?, but the solution does...

Why does this Rust binary tree overflow its stack in tests? [duplicate]

Why does this Rust binary tree overflow its stack in tests? [duplicate] This question already has an answer here: I've written a binary tree-like structure, but I've been getting stack-overflow errors in some of my stress tests. I've reduced the error-causing code down to the following: struct Node { index: usize, right: Option>, } struct BoxedTree { root: Option<Box<Node>>, } fn build_degenerate() { let mut t = BoxedTree { root: Some(Box::new(Node { index: 0, right: None, })), }; let mut n = t.root.as_mut().unwrap(); for i in 1..50000 { let cur = n; let p = &mut cur.right; *p = Some(Box::new(Node { index: i, right: None, })); n = p.as_mut().unwrap(); } println!("{}", n.index); } fn main() { build_degenerate(); } #[cfg(test)] mod tests { use super::*; #[test] fn mytest() { ...

What does “borrowed data cannot be stored outside of its closure” mean?

What does “borrowed data cannot be stored outside of its closure” mean? When compiling the following code: fn main() { let mut fields = Vec::new(); let pusher = &mut |a: &str| { fields.push(a); }; } The compiler gives me the following error: error: borrowed data cannot be stored outside of its closure --> src/main.rs:4:21 | 3 | let pusher = &mut |a: &str| { | ------ --------- ...because it cannot outlive this closure | | | borrowed data cannot be stored into here... 4 | fields.push(a); | ^ cannot be stored outside of its closure What does this error mean, and how can I fix my code? 1 Answer 1 It means exactly what it says: that the data you are borrowing only lives for the duration of the closure. Attempting to store it outside of the closure would expose the code to memory unsafety. This...