rust

Why does _ destroy at the end of statement?

大憨熊 提交于 2020-01-23 05:30:08
问题 I've seen a few other questions and answers stating that let _ = foo() destroys the result at the end of the statement rather than at scope exit, which is what let _a = foo() does. I am unable to find any official description of this, nor any rationale for this syntax. I'm interested in a few inter-twined things: Is there even a mention of it in the official documentation? What is the history behind this choice? Is it simply natural fall-out from Rust's binding / destructuring rules? Is it

How do I print a vector of u8 as a string?

荒凉一梦 提交于 2020-01-23 05:25:09
问题 Here's my code: let mut altbuf: Vec<u8> = Vec::new(); // Stuff here... match stream.read_byte() { Ok(d) => altbuf.push(d), Err(e) => { println!("Error: {}", e); doneflag = true; } } for x in altbuf.iter() { println!("{}", x); } The code prints u8 bytes which are correct, but I can't figure out for the life of me how to convert a vector of pure u8 bytes into a string? The only other answer to a similar question on stack overflow assumes that you're working with a vector of type &[u8]. 回答1: If

[The RUST Programming Language]Chapter 4. Understanding Ownership (2)

烈酒焚心 提交于 2020-01-23 02:38:47
Understanding Ownership References and Borrowing 引用和借用 Mutable References 可修改引用 Dangling References 摇摆引用 The Rules of References 引用的规则 The Slice Type 切片类型 String Slices String切片 String Literals Are Slices 字符串都是切片 String Slices as Parameters 字符串切片作为形参 Other Slices 其它切片 Summary 总结 References and Borrowing 引用和借用 在上一章的例子中,我们不得不使用元组返回调用函数时传入的 String ,这样才能继续在 calculate_length 中使用这个 String ,这是由于 String 会被移动到 calculate_length 中。 这里有另外一个例子,我们在定义 calculate_length 函数时将一个引用作为入参,这种方式调用,就不会去抢夺变量对值的所有权: fn main ( ) { let s1 = String : : from ( "hello" ) ; let len = calculate_length ( & s1 ) ; println ! (

Rust “use” vs. C++ “using namespace”

不打扰是莪最后的温柔 提交于 2020-01-22 18:33:14
问题 Is it considered bad style to declare multiple "use" statements in Rust? I am a C++ programmer that recently began trying out Rust. One thing I've noticed as I review Rust code is that in many Rust programs there will be a bunch of use statements at the top of the program. Coming from C++, it was discouraged to use using namespace std especially when making header files, but that doesn't seem to be the case in most of the Rust programs I've seen. So which of the following trivial examples is

How to implement a stream of futures for a blocking call using futures.rs and Redis PubSub?

落爺英雄遲暮 提交于 2020-01-22 14:39:30
问题 I'm trying to create a system by which my application can receive streaming data from a Redis PubSub channel and process it. The Redis driver that I'm using, along with all other Redis drivers for Rust that I've seen, use a blocking operation to get data from the channel that only returns a value when it receives data: let msg = match pubsub.get_message() { Ok(m) => m, Err(_) => panic!("Could not get message from pubsub!") }; let payload: String = match msg.get_payload() { Ok(s) => s, Err(_)

Cannot borrow `*self` as mutable more than once at a time when returning a Result containing a reference

落花浮王杯 提交于 2020-01-22 03:32:28
问题 Why is the following invalid and what should I do instead to make it work? struct Foo; impl Foo { fn mutable1(&mut self) -> Result<(), &str> { Ok(()) } fn mutable2(&mut self) -> Result<(), &str> { self.mutable1()?; self.mutable1()?; Ok(()) } } This code yields: error[E0499]: cannot borrow `*self` as mutable more than once at a time --> src/lib.rs:10:9 | 8 | fn mutable2(&mut self) -> Result<(), &str> { | - let's call the lifetime of this reference `'1` 9 | self.mutable1()?; | ---- - returning

Is there any way to create a async stream generator that yields the result of repeatedly calling a function?

懵懂的女人 提交于 2020-01-22 02:21:25
问题 I want to build a program that collects weather updates and represents them as a stream. I want to call get_weather() in an infinite loop, with 60 seconds delay between finish and start . A simplified version would look like this: async fn get_weather() -> Weather { /* ... */ } fn get_weather_stream() -> impl futures::Stream<Item = Weather> { loop { tokio::timer::delay_for(std::time::Duration::from_secs(60)).await; let weather = get_weather().await; yield weather; // This is not supported //

How to use a reference to a FnOnce closure?

你说的曾经没有我的故事 提交于 2020-01-21 20:40:10
问题 I have a function which needs to pass a closure argument recursively use std::cell::RefCell; use std::rc::Rc; pub struct TreeNode { val: i32, left: Option<Rc<RefCell<TreeNode>>>, right: Option<Rc<RefCell<TreeNode>>>, } pub fn pre_order<F>(root: Option<Rc<RefCell<TreeNode>>>, f: F) where F: FnOnce(i32) -> (), { helper(&root, f); fn helper<F>(root: &Option<Rc<RefCell<TreeNode>>>, f: F) where F: FnOnce(i32), { match root { Some(node) => { f(node.borrow().val); helper(&node.borrow().left, f);

How to use a reference to a FnOnce closure?

纵饮孤独 提交于 2020-01-21 20:35:06
问题 I have a function which needs to pass a closure argument recursively use std::cell::RefCell; use std::rc::Rc; pub struct TreeNode { val: i32, left: Option<Rc<RefCell<TreeNode>>>, right: Option<Rc<RefCell<TreeNode>>>, } pub fn pre_order<F>(root: Option<Rc<RefCell<TreeNode>>>, f: F) where F: FnOnce(i32) -> (), { helper(&root, f); fn helper<F>(root: &Option<Rc<RefCell<TreeNode>>>, f: F) where F: FnOnce(i32), { match root { Some(node) => { f(node.borrow().val); helper(&node.borrow().left, f);

Why do I get the error “cannot borrow x as mutable more than once”?

喜欢而已 提交于 2020-01-21 19:38:11
问题 I'm implementing a parser in Rust. I have to update the index for the lookahead, but when I call self.get() after self.current() I get an error: cannot borrow *self as mutable more than once at a time It's confusing since I'm new to Rust. #[derive(Debug)] pub enum Token { Random(String), Undefined(String), } struct Point { token: Vec<Token>, look: usize, } impl Point { pub fn init(&mut self){ while let Some(token) = self.current(){ println!("{:?}", token); let _ = self.get(); } } pub fn