Hi I'm pretty new to Rust.I was writing a macro these days and I get an error ,can someone explain why did the errors occur and how to fix it?Thanks.
code:
playground
/*
* @Descripttion:
* @version:
* @Author: Caviar-X
* @Date: 2021-06-18 22:05:38
* @LastEditors: Please set LastEditors
* @LastEditTime: 2021-06-24 11:57:56
*/
use std::io::stdin;
/*fn input(num : i32) -> Vec<i128> {//input function
if num < 1 {
panic!("num cannot smaller than 1!");
}
let mut inpstr = String::new();
let mut result:Vec<i128> = Vec::new();
stdin().read_line(&mut inpstr).expect("Failed to read");
let strt : Vec<&str> = inpstr.split_whitespace().collect();
for s in strt {
result.push(s.parse::<i128>().unwrap());
}
result
}*/
fn is_digit(s: String) -> bool {
let chars_are_numeric: Vec<bool> = s.chars().map(|c| c.is_numeric()).collect();
!chars_are_numeric.contains(&false)
}
fn is_float(s: String) -> bool {
s.contains(".")
&& is_digit(s[0..s.find(".").unwrap()].to_string())
&& is_digit(s[s.find(".").unwrap() + 1..s.len()].to_string())
}
macro_rules! read {
($(&mut $key:expr),*) => {
let mut inpstr = String::new();
let mut result:Vec<&str> = Vec::new();
stdin()
.read_line(&mut inpstr)
.expect("Error: Failed to read.");
result = inpstr.split_whitespace().collect();
let mut i = 0;
$(
loop {
if i == result.len() {
break;
} else if is_digit(String::from(result[i])) {
$key = result[i].parse::<i128>().unwrap();
} else if is_float(result[i].to_string()) {
$key = result[i].parse::<f64>().unwrap();
}
else {
$key = result[i];
}
i+=1;
}
)*
};
}
fn main() {
/*
let mut a = 0;
read!(&mut a);
assert_eq!(a,5);
*/
}
Stanard Error:
error[E0308]: mismatched types
--> src/main.rs:49:24
|
49 | $key = result[i].parse::<f64>().unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `i128`, found `f64`
...
61 | read!(&mut a);
| -------------- in this macro invocation
|
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0308]: mismatched types
--> src/main.rs:52:24
|
52 | $key = result[i];
| ^^^^^^^^^ expected `i128`, found `&str`
...
61 | read!(&mut a);
| -------------- in this macro invocation
|
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0308`.
error: could not compile `OI`
To learn more, run the command again with --verbose.
By the way,I wrote this code in C ways,so It may not safe,if you have suggestions to my code,welcome to bring up it.