rust

How to multiply/divide/add/subtract numbers of different types?

好久不见. 提交于 2020-01-10 03:45:08
问题 I'm working through the second edition of the Rust handbook, and decided to try and make the classic Celsius-to-Fahrenheit converter: fn c_to_f(c: f32) -> f32 { return ( c * ( 9/5 ) ) + 32; } Compiling this with cargo build will yield the compile-time error: error[E0277]: the trait bound `f32: std::ops::Mul<{integer}>` is not satisfied --> src/main.rs:2:12 | 2 | return (c * (9 / 5)) + 32; | ^^^^^^^^^^^^^ the trait `std::ops::Mul<{integer}>` is not implemented for `f32` | = note: no

Why is using return as the last statement in a function considered bad style?

守給你的承諾、 提交于 2020-01-10 03:28:07
问题 I was reading through the Rust documentation and came across the following example and statement Using a return as the last line of a function works, but is considered poor style: fn foo(x: i32) -> i32 { if x < 5 { return x; } return x + 1; } I know I could have written the above as fn foo(x: i32) -> i32 { if x < 5 { return x; } x + 1 } but I am more tempted to write the former, as that is more intuitive. I do understand that the function return value should be used as an expression so the

How can I perform parallel asynchronous HTTP GET requests with reqwest?

☆樱花仙子☆ 提交于 2020-01-10 02:04:12
问题 The async example is useful, but being new to Rust and Tokio, I am struggling to work out how to do N requests at once, using URLs from a vector, and creating an iterator of the response HTML for each URL as a string. How could this be done? 回答1: As of reqwest 0.10: use futures::{stream, StreamExt}; // 0.3.1 use reqwest::Client; // 0.10.0 use tokio; // 0.2.4, features = ["macros"] const PARALLEL_REQUESTS: usize = 2; #[tokio::main] async fn main() { let client = Client::new(); let urls = vec![

Is there a way to perform an index access to an instance of a struct?

怎甘沉沦 提交于 2020-01-09 11:59:08
问题 Is there a way to perform an index access to an instance of a struct like this: struct MyStruct { // ... } impl MyStruct { // ... } fn main() { let s = MyStruct::new(); s["something"] = 533; // This is what I need } 回答1: You can use the Index and IndexMut traits. use std::ops::{Index, IndexMut}; struct Foo { x: i32, y: i32 } impl<'a> Index<&'a str> for Foo { type Output = i32; fn index(&self, s: &&'a str) -> &i32 { // ' match *s { "x" => &self.x, "y" => &self.y, _ => panic!("unknown field: {}

Rust Trait object conversion

人盡茶涼 提交于 2020-01-09 11:40:08
问题 The following code won't compile due to two instances of this error: error[E0277]: the trait bound Self: std::marker::Sized is not satisfied I don't understand why Sized is required in this instance as both &self and &Any are pointers and the operation does not require knowledge of the size of the structure that implements the trait, it only requires knowledge of the pointer itself and the type it is converting from and to, which it will have because &self is generic when implemented inside a

Remove single trailing newline from String without cloning

梦想与她 提交于 2020-01-09 11:02:05
问题 I have written a function to prompt for input and return the result. In this version the returned string includes a trailing newline from the user. I would like to return the input with that newline (and just that newline) removed: fn read_with_prompt(prompt: &str) -> io::Result<String> { let stdout = io::stdout(); let reader = io::stdin(); let mut input = String::new(); print!("{}", prompt); stdout.lock().flush().unwrap(); reader.read_line(&mut input)?; // TODO: Remove trailing newline if

Is it possible to implement methods on type aliases?

人走茶凉 提交于 2020-01-09 10:40:08
问题 Consider the following implementation: pub struct BST { root: Link, } type Link = Option<Box<Node>>; struct Node { left: Link, elem: i32, right: Link, } impl Link { /* misc */ } impl BST { /* misc */ } I keep getting the error: cannot define inherent impl for a type outside of the crate where the type is defined; define and implement a trait or new type instead I was able to find others had this same issue back in February, but there was seemingly no solution at the time. Is there any fix or

Can't understand Rust module system

孤人 提交于 2020-01-09 08:13:27
问题 I created a simple project for educational purpose, so I have a main function and 3 traits Battery , Display and GSM and implementations for them. I want the the main function to be in file main.rs and the 3 traits in another file called phone.rs: phone.rs mod phone{ pub struct Battery{ model : String, hours_idle : i16, hours_talk : i16 } pub struct Display{ size : i16, number_of_colors : i32 } pub struct GSM{ model : String, manufactor : String, price : f32, owner : String, battery: Battery,

Can't understand Rust module system

旧时模样 提交于 2020-01-09 08:12:31
问题 I created a simple project for educational purpose, so I have a main function and 3 traits Battery , Display and GSM and implementations for them. I want the the main function to be in file main.rs and the 3 traits in another file called phone.rs: phone.rs mod phone{ pub struct Battery{ model : String, hours_idle : i16, hours_talk : i16 } pub struct Display{ size : i16, number_of_colors : i32 } pub struct GSM{ model : String, manufactor : String, price : f32, owner : String, battery: Battery,

Type must be known in this context when using Iterator::collect

孤街醉人 提交于 2020-01-09 03:50:06
问题 I want to get a length of a string which I've split: fn fn1(my_string: String) -> bool { let mut segments = my_string.split("."); segments.collect().len() == 55 } fn main() {} error[E0619]: the type of this value must be known in this context --> src/main.rs:3:5 | 3 | segments.collect().len() == 55 | ^^^^^^^^^^^^^^^^^^^^^^^^ How can I fix that error? 回答1: On an iterator, the collect method can produce many types of collections: fn collect<B>(self) -> B where B: FromIterator<Self::Item>, Types