rust

Why does rust's read_line function use a mutable reference instead of a return value?

穿精又带淫゛_ 提交于 2021-01-27 12:52:57
问题 Consider this code to read the user input in rust use std::io; fn main() { let mut input = String::new(); io::stdin() .read_line(&mut input) .expect("error: unable to read user input"); println!("{}", input); } why is there no way to do it like this? use std::io; fn main() { let mut input = io::stdin() .read_line() .expect("error: unable to read user input"); println!("{}", input); } it would be more convenient to other languages 回答1: The reason is that read_line is not optimized for small

How can I use a custom hash function in a HashSet or HashMap?

不羁的心 提交于 2021-01-27 12:51:26
问题 Since SipHasher is too slow for my use case, I'm trying to implement a custom hash function. I found an example which I used as base to get everything compiling. My current code looks like this: use std::collections::hash_state::{DefaultState}; use std::collections::{HashMap, HashSet}; use std::default::Default; use std::hash::{Hash, Hasher, SipHasher}; use std::marker; pub struct FnvHasher(u64); impl Default for FnvHasher { fn default() -> FnvHasher { FnvHasher(0xcbf29ce484222325) } } impl

Borrowed RefCell does not last long enough when iterating over a list

折月煮酒 提交于 2021-01-27 12:30:13
问题 I'm trying to implement a linked list to understand smart pointers in Rust. I defined a Node : use std::{cell::RefCell, rc::Rc}; struct Node { val: i32, next: Option<Rc<RefCell<Node>>>, } and iterate like fn iterate(node: Option<&Rc<RefCell<Node>>>) -> Vec<i32> { let mut p = node; let mut result = vec![]; loop { if p.is_none() { break; } result.push(p.as_ref().unwrap().borrow().val); p = p.as_ref().unwrap().borrow().next.as_ref(); } result } the compiler reports an error: error[E0716]:

How do I declare a generic function which can add together references to sparse vectors? [duplicate]

柔情痞子 提交于 2021-01-27 12:25:05
问题 This question already has answers here : How to write a trait bound for adding two references of a generic type? (1 answer) How do I require a generic type implement an operation like Add, Sub, Mul, or Div in a generic function? (2 answers) Closed 1 year ago . I'm trying to use the sprs crate (version 0.6.3 ) to manipulate sparse vectors. I'd like to add two vectors together. I started off with an implementation of the Add trait, then simplified this to an implementation function. Finally, I

Error on Future generator closure: Captured variable cannot escape `FnMut` closure body

会有一股神秘感。 提交于 2021-01-27 12:03:28
问题 I want to create a simple websocket server. I want to process the incoming messages and send a response, but I get an error: error: captured variable cannot escape `FnMut` closure body --> src\main.rs:32:27 | 32 | incoming.for_each(|m| async { | _________________________-_^ | | | | | inferred to be a `FnMut` closure 33 | | match m { 34 | | // Error here... 35 | | Ok(message) => do_something(message, db, &mut outgoing).await, 36 | | Err(e) => panic!(e) 37 | | } 38 | | }).await; | |_____^

Ctrl-S input event in Windows console with ReadConsoleInputW

北城以北 提交于 2021-01-27 11:44:59
问题 I am using ReadConsoleInputW to read Windows 10 console input. I want to be able to detect when Ctrl + S is pressed. Using the code I have, I can detect Ctrl + Q without issue, but I'm not seeing anything for Ctrl + S . Is Ctrl + S even detectable? The below is the sequence of INPUT_RECORD I read when pressing Ctrl + S a few times, followed by Ctrl + Q . Key { key_down: true, repeat_count: 1, key_code: 17, scan_code: 29, wide_char: 0, control_key_state: 40 } Key { key_down: true, repeat_count

How can I use internal mutability with generic type in Rust?

家住魔仙堡 提交于 2021-01-27 11:43:11
问题 I would like to design a struct in Rust that can be constructed with an object that implements the Digest trait, and abstract the behavior of the hash behind a method. Here's a simple example that doesn't compile: use digest::Digest; struct Crypto<D: Digest> { digest: D, } impl<D> Crypto<D> where D: Digest, { pub fn hash(&self, data: &[u8]) -> Vec<u8> { self.digest.chain(&data).finalize_reset().to_vec() } } This fails to compile because self is immutably borrowed in the method signature, so

How to make a local dependency depend on a feature in Cargo?

三世轮回 提交于 2021-01-27 11:37:43
问题 Given this small library which uses local crates in subdirectories, how would I make one of the dependencies optional, depending on if a feature is enabled? [package] name = "image_load" description = "Small wrapper for image reading API's." version = "0.1.0" [features] default = ["use_png"] [dependencies] [dependencies.image_load_ppm] path = "ppm" # How to make this build _only_ when 'use_png' feature is enabled? [dependencies.image_load_png] path = "png" While I read the documentation, this

How to delay destruction of unnamed objects?

大城市里の小女人 提交于 2021-01-27 09:34:26
问题 I am using the TempDir struct to create and remove folders on disk. The TempDir itself is not referenced in the code apart from its construction. Since the compiler warns about unused objects, I tried (un)naming the TempDir-struct to _ but this results in the struct immediately being destroyed. Is there a nice solution to this? See example code, compare one to two : pub struct Res; impl Drop for Res { fn drop(&mut self) { println!("Dropping self!"); } } fn one() { println!("one"); let r = Res

error: failed to run custom build command for `openssl v0.9.24`

余生颓废 提交于 2021-01-27 07:16:26
问题 I want to install cargo-apk cargo install cargo-apk to my system (Linux Mint), but I'm getting this error error: failed to run custom build command for `openssl v0.9.24` Caused by: process didn't exit successfully: `/tmp/cargo-install7N44TO/release/build/openssl-65bb03053b1fc095/build-script-build` (exit code: 101) --- stderr thread 'main' panicked at 'Unable to detect OpenSSL version', /home/jiri/.cargo/registry/src/github.com-1ecc6299db9ec823/openssl-0.9.24/build.rs:16:14 note: run with