rust

Should .cloned() be before or after .filter()

纵饮孤独 提交于 2020-01-03 18:33:10
问题 Let's say that I have vector and I want just keep the even elements. I would need to used cloned() and filter() . For example: fn main() { let my_vec: Vec<i32> = vec![1,2,3,4]; let my_vec_1: Vec<i32> = my_vec.iter().cloned().filter(|&x| x % 2 == 0).collect(); println!("{:?}", my_vec_1); let my_vec_2: Vec<i32> = my_vec.iter().filter(|&x| x % 2 == 0).cloned().collect(); println!("{:?}", my_vec_2); } Both approaches work. Using cloned() after filter() seems a little bit more efficient. Because

Silent error while accessing Redis

主宰稳场 提交于 2020-01-03 17:08:09
问题 I am a newbie with Rust. I am using the crate redis = "0.3.1" but the program simply exits without raising a panic. The only thing I am doing different is that the database is different. extern crate redis; use redis::*; use std::string::String; use std::collections::HashSet; fn main() { read_meta_keys_redis("myset".to_string()); } fn read_meta_keys_redis(key: String) -> redis::RedisResult<()> { println!("22{}", key); let client = try!(redis::Client::open("redis://127.0.0.1:6379/2")); let con

How to match a file extension represented as an OsStr?

微笑、不失礼 提交于 2020-01-03 16:56:19
问题 I am trying to match against a file extension: let file_path = std::path::Path::new("index.html"); let content_type = match file_path.extension() { None => "", Some(os_str) => match os_str { "html" => "text/html", "css" => "text/css", "js" => "application/javascript", }, }; The compiler says: error[E0308]: mismatched types --> src/main.rs:6:13 | 6 | "html" => "text/html", | ^^^^^^ expected struct `std::ffi::OsStr`, found str | = note: expected type `&std::ffi::OsStr` found type `&'static str`

Can I use a method or a function as a closure?

落爺英雄遲暮 提交于 2020-01-03 16:53:14
问题 I have some methods on a struct that I'd like to pass around as parameters. I'm pretty sure the only way to pass around functions is by using closures. Is there a way I can do this without doing || { self.x() } ? 回答1: You can absolutely use a method or a function as a closure. You use the full path to the function or method, including trait methods: A free function: struct Monster { health: u8, } fn just_enough_attack(m: Monster) -> u8 { m.health + 2 } fn main() { let sully = Some(Monster {

How do I read an Iron Request in both middleware and the handler?

为君一笑 提交于 2020-01-03 16:46:12
问题 I'm working on a small API in Rust and am not sure how to access a Request from Iron in two places. The Authentication middleware reads the Request once for a token and the actual route tries to read it again if the path is allowed (currently there is no check). This gives me an EOF error as the request has already been read. I can't seem to easily clone the request and I believe it must be mutable in order to read the body. extern crate iron; extern crate router; extern crate rustc_serialize

Is there a trait for only primitive types that I can use in a generic function?

北慕城南 提交于 2020-01-03 16:01:08
问题 I am trying to write a generic function which will try to convert a string to a number type like i32 , f64 etc. If the string is not convertible then it will return 0 . I am looking for an appropriate trait bound to use in my generic function below: use std::str::FromStr; fn get_num_from_str<T: FromStr>(maybe_num_str: &String) -> T { let maybe_num = T::from_str(maybe_num_str.as_str()); if maybe_num.is_ok() { return maybe_num.unwrap(); } 0 as T } fn main() { let num_str = String::from("12");

What is the idiomatic way to have a private function tested?

大城市里の小女人 提交于 2020-01-03 15:23:52
问题 The Rust book says that using a "tests" module is the idiomatic way to have unit tests. But I cannot see a function from the super module in the tests module if that function is not marked 'pub'. How should one test internal functions then? My first instinct was to look for a way to #ifdef the keyword pub . I have done this in the past for C++ testing. For Rust what I have done is simply have tests for private functions in the module and then tests for the public interface in the "tests"

What is the idiomatic way to have a private function tested?

老子叫甜甜 提交于 2020-01-03 15:23:12
问题 The Rust book says that using a "tests" module is the idiomatic way to have unit tests. But I cannot see a function from the super module in the tests module if that function is not marked 'pub'. How should one test internal functions then? My first instinct was to look for a way to #ifdef the keyword pub . I have done this in the past for C++ testing. For Rust what I have done is simply have tests for private functions in the module and then tests for the public interface in the "tests"

How to wrap a call to a FFI function that uses VarArgs in Rust?

此生再无相见时 提交于 2020-01-03 14:25:06
问题 mexPrintf , just like printf , accepts a varargs list of arguments, but I don't know what the best way to wrap this is in Rust. There is a RFC for variadic generics, but what can we do today? In this example, I want to print of the number of inputs and outputs, but the wrapped function just prints garbage. Any idea how to fix this? #![allow(non_snake_case)] #![allow(unused_variables)] extern crate mex_sys; use mex_sys::mxArray; use std::ffi::CString; use std::os::raw::c_int; use std::os::raw:

How can I define a Rust function type which returns its own type?

我的梦境 提交于 2020-01-03 14:17:37
问题 I'm learning Rust, and still very much trying to get my head around it. Consider the following Go definition: type FnType func(paramType) FnType It's just a function that returns a function of the same type. Can something similar be implemented in Rust? And, ideally, can it be done generically, so that paramType is specified by the client? 回答1: I did some digging in the docs and took to the playground and I think I've been able to answer this myself, although it does require an intermediary