rust

A simple formula interpreter

末鹿安然 提交于 2020-01-16 07:08:51
问题 To understand Rust, I am trying to implement a little formula interpreter. An expression can only be an integer, a sum, a variable ( Term ) or an assignment ( Set ). We can then evaluate an expression. Since symbols with no associated values can appear in an expression, its evaluation yields another expression (and not necessarily an integer). The values of the variables (if there are any) can be found in a hash table. use std::rc::Rc; use std::collections::HashMap; enum Expr { Integer(i32),

A simple formula interpreter

只愿长相守 提交于 2020-01-16 07:08:23
问题 To understand Rust, I am trying to implement a little formula interpreter. An expression can only be an integer, a sum, a variable ( Term ) or an assignment ( Set ). We can then evaluate an expression. Since symbols with no associated values can appear in an expression, its evaluation yields another expression (and not necessarily an integer). The values of the variables (if there are any) can be found in a hash table. use std::rc::Rc; use std::collections::HashMap; enum Expr { Integer(i32),

Rust: Read and map lines from stdin and handling different error types

时光毁灭记忆、已成空白 提交于 2020-01-16 05:36:07
问题 I'm learning Rust and trying to solve some basic algorithm problems with it. In many cases, I want to read lines from stdin, perform some transformation on each line and return a vector of resulting items. One way I did this was like this: // Fully working Rust code let my_values: Vec<u32> = stdin .lock() .lines() .filter_map(Result::ok) .map(|line| line.parse::<u32>()) .filter_map(Result::ok) .map(|x|x*2) // For example .collect(); This works but of course silently ignores any errors that

What is the most idiomatic way to merge two error types?

◇◆丶佛笑我妖孽 提交于 2020-01-16 05:35:06
问题 I have a type Foo whose methods may "raise" errors of an associated type Foo::Err . pub trait Foo { type Err; fn foo(&mut self) -> Result<(), Self::Err>; } I have another trait Bar with a method intended to process a Foo . Bar may issue errors of its own (specified by an associated type Bar::Err ), but it may also encounter errors generated by the Foo it is processing. I can see two ways to do handle, but I don't know which one would be the most idiomatic to Rust. The first one embeds a

Why does pattern matching on &Option<T> yield something of type Some(&T)?

时光总嘲笑我的痴心妄想 提交于 2020-01-16 05:25:07
问题 I have a tiny playground example here fn main() { let l = Some(3); match &l { None => {} Some(_x) => {} // x is of type &i32 } } I'm pattern matching on &Option and if I use Some(x) as a branch, why is x of type &i32 ? 回答1: The type of the expression &l you match against is &Option<i32> , so if we are strict the patterns should be &None and &Some(x) , and if we use these patterns, the type of x indeed is i32 . If we omit the ampersand in the patterns, as you did in your code, it first looks

Is it possible to collect an iterator to populate a collection backwards?

自作多情 提交于 2020-01-16 04:50:08
问题 Is it possible to collect an iterator such that it populates a collection backwards, such as using push_front in a VecDeque ? It's possible to collect into a Vec and then reverse it, but it seems like it should be unnecessary with data structures explicitly supporting this capability. I'd like to avoid writing an explicit for loop if possible. 回答1: Yes, it's possible: use std::collections::VecDeque; fn main() { let v: VecDeque<_> = (0..=2).collect_rev(); assert_eq!(v, [2, 1, 0]); let v: Vec<_

Rust's drain, iterator dropped … “removes any remaining elements”

倖福魔咒の 提交于 2020-01-16 00:46:07
问题 On page 327 of Programming Rust you can find the following statement However, unlike the into_iter() method, which takes the collection by value and consumes it, drain merely borrows a mutable references to the collection, and when the iterator is dropped, it removes any remaining elements from the collection, and leaves it empty. I'm confused at what it means it says it removes any remaining elements from the collection? I can see with this code when the iterator is dropped the remaining

五分钟入门rust语言

帅比萌擦擦* 提交于 2020-01-16 00:29:07
1. 入坑rust 1.1 rust发展历程 2006年,Mozilla 员工 “Graydon Hoare” 开发了Rust。 2015年5月15日,Rust编程语言核心团队正式宣布发布Rust 1.0版本,之后连续4年,在Stack Overflow开发者「最受喜爱编程语言」评选中获得第一名。 2019年7月4日,社交网络巨头Facebook联合其他100个行业巨头,对外宣布准备建设Libra(天秤座)项目。该项目的技术特点是:构建于区块链技术之上,并且基于Rust实现。 2019年7月18日,微软安全响应中心(MSRC)发文宣称:我们需要更安全的系统编程语言。 在suricata5.0上,rust已经成为一个必选组件,被用来编写应用层解析代码。 需要基于suricata开发项目的我,不得不入坑rust了。 1.2 rust安装 rustup 是rust官方的版本管理工具。应当作为安装 Rust 的首选。 在linux/mac下,运行一条命令就行了: curl https : / / sh . rustup . rs - sSf | sh 但是由于众所周知的防火墙问题,我们需要配置一下中科大的源。 详细参考:https://zhuanlan.zhihu.com/p/26944087 2. Rust初印象 rust对标c/c++,是一个编译型系统级编程语言

error: `line` does not live long enough (but I know it does)

醉酒当歌 提交于 2020-01-15 14:24:28
问题 I am trying to make some kind of ffi to a library written in C, but got stuck. Here is a test case: extern crate libc; use libc::{c_void, size_t}; // this is C library api call unsafe fn some_external_proc(_handler: *mut c_void, value: *const c_void, value_len: size_t) { println!("received: {:?}" , std::slice::from_raw_buf( &(value as *const u8), value_len as usize)); } // this is Rust wrapper for C library api pub trait MemoryArea { fn get_memory_area(&self) -> (*const u8, usize); } impl

Can't read a simple payload making HTTP request via hyper::client::Client: the trait bound `Body: Future` is not satisfied

浪尽此生 提交于 2020-01-15 12:26:05
问题 I am attempting to convert a Result to a Buffer : let ufc_root: String = String::from("https://www.ufc.com/athletes/all?filters%5B0%5D=status%3A23"); // let ufc_root: String = String::from("https://www.google.com"); let https = HttpsConnector::new(4).unwrap(); let client = Client::builder().build::<_, hyper::Body>(https); client .get(ufc_root.parse::<hyper::Uri>().unwrap()) .and_then(|res| { println!("http status code: {}", res.status()); println!("http response headers:\n{:?}: ", res.headers