rust

Textfile-parsing function fails to compile owing to type-mismatch error

我只是一个虾纸丫 提交于 2020-01-24 19:10:27
问题 I'm trying to parse a simple config text file, which contains one three-word entry per line, laid out as follows: ITEM name value ITEM name value //etc. I've reproduced the function which does the parsing (and the subsequent compilation error) here (and on the Rust Playpen): pub fn parse(path: &Path) -> config_struct { let file = File::open(&path).unwrap(); let reader = BufReader::new(&file); let line_iterator = reader.lines(); let mut connection_map = HashMap::new(); let mut target_map =

Traits with stricter associated type bounds than supertrait

こ雲淡風輕ζ 提交于 2020-01-24 18:58:22
问题 I have a simple trait with an associated type with no bounds. trait Board { type Move; fn moves(&self) -> Vec<Self::Move>; } I also want to use this trait as a supertrait. In particular, I want my new subtrait to have stricter bounds on the associated type. Something like this: trait TextBoard: Board { type Move: fmt::Debug; // Trying to tighten bounds on associated type fn printMoves(&self) { println!("{:?}", self.moves()); } } The example is highly simplified, but seems to show the problem:

Why does Vec<T>::split_at_mut borrow the vector for the rest of the scope?

断了今生、忘了曾经 提交于 2020-01-24 17:32:06
问题 Vec<T> has two methods: fn push(&mut self, value: T) fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) They both take a mutable reference to the vector. But the scope of the borrow seems to be different, e.g: fn works() { let mut nums: Vec<i64> = vec![1,2,3,4]; nums.push(5); println!("{}", nums.len()); } fn doesnt_work() { let mut nums: Vec<i64> = vec![1,2,3,4]; let (l,r) = nums.split_at_mut(2); println!("{}", nums.len()); } fn also_works() { let mut nums: Vec<i64> = vec![1,2,3,4

How can I use Serde's custom (de)serialization to update a subset of arbitrary input?

梦想的初衷 提交于 2020-01-24 15:28:26
问题 I need to update specific fields of an arbitrary input file without touching any keys or values that my program does not know about. Here is an example input file: { "alpha": { "a": 1, "z": 2 }, "beta": "b" } I'd like to update alpha.a by 100: { "alpha": { "a": 101, "z": 2 }, "beta": "b" } It is possible to do this with types like serde_json::Value and toml::value::Value, but this code is very cumbersome: extern crate serde; // 1.0.66 extern crate serde_json; // 1.0.21 use serde_json::Value;

Complex trait requirements on struct

独自空忆成欢 提交于 2020-01-24 15:05:46
问题 I have a fairly complex trait set up and I'm having trouble lining the pieces up. Right now it looks roughly like this: /// Trait for models which can be gradient-optimized. pub trait Optimizable { type Data; type Target; // The contract // } /// Trait for optimization algorithms. pub trait OptimAlgorithm<M : Optimizable> { // The contract // } Now I want to be able to allow a struct implementing OptimAlgorithm to be a field in a struct implementing Optimizable . This would look something

In Rust, what exactly are mutable and immutable borrows?

久未见 提交于 2020-01-24 13:53:06
问题 I'm stuck with the Rust concepts of borrowing and mutable : #[derive(Debug)] struct Rectangle { height: u32, width: u32, } fn mut_area(rect_mut: &mut Rectangle) -> u32 { rect_mut.width /= 2; rect_mut.height * rect_mut.width } fn mut_string(s: &mut String) -> &str { s.push_str("!"); let len = s.len(); &s[0..len / 2] } fn main() { let mut rect = Rectangle { height: 50, width: 40, }; println!("original rect: {:?}", rect); let a = mut_area(&mut rect); println!("area of rect: {}", a); println!(

In Rust, what exactly are mutable and immutable borrows?

烈酒焚心 提交于 2020-01-24 13:52:00
问题 I'm stuck with the Rust concepts of borrowing and mutable : #[derive(Debug)] struct Rectangle { height: u32, width: u32, } fn mut_area(rect_mut: &mut Rectangle) -> u32 { rect_mut.width /= 2; rect_mut.height * rect_mut.width } fn mut_string(s: &mut String) -> &str { s.push_str("!"); let len = s.len(); &s[0..len / 2] } fn main() { let mut rect = Rectangle { height: 50, width: 40, }; println!("original rect: {:?}", rect); let a = mut_area(&mut rect); println!("area of rect: {}", a); println!(

Why is a immutable pointer to a static immutable variable not Sync?

孤人 提交于 2020-01-24 13:06:28
问题 A static global C string (as in this answer) doesn't have the Sync trait. pub static MY_STRING: &'static *const u8 = "hello" as const *u8; // TODO: Simple assertion showing it's not Sync ;) Sync is described as The precise definition is: a type T is Sync if &T is thread-safe. In other words, there is no possibility of data races when passing &T references between threads. It seems like this is entirely readonly and has static lifetime, so why isn't it safe to pass a reference? 回答1: The

How do I not borrow an Option when matching?

≯℡__Kan透↙ 提交于 2020-01-24 12:26:13
问题 I have the following code: fn remove_descendent(&mut self, key: &K) -> Option<V> { if self.left.is_some() && self.left.as_ref().unwrap().key == *key { return self.remove_left(); } // more of the function } This feels gross to me. Instead of checking is_some and then unwrapping. I figured what I really should be doing is using a match statement to deconstruct the Option represented by the left variable like so: fn remove_descendent(&mut self, key: &K) -> Option<V> { match self.left { Some(ref

How can I create a stream where the items are based on items that the stream previously returned?

☆樱花仙子☆ 提交于 2020-01-24 11:48:05
问题 I have a function that generates a futures::Stream based on an argument. I want to call this function multiple times and flatten the streams together. Complicating matters is the fact that I want to feed the values returned by the stream back as the argument to the original function. Concretely, I have a function that returns a stream of numbers down to zero: fn numbers_down_to_zero(v: i32) -> impl Stream<Item = i32> { stream::iter((0..v).rev()) } I want to call this function starting at 5.