这是一个人为的例子,但我相信如果我能够做到这一点,我可以将它应用于我的具体案例.
extern crate num;
extern crate rayon;
use rayon::prelude::*;
use num::Float;
fn sqrts<T: Float>(floats: &Vec<T>) -> Vec<T> {
floats.par_iter().map(|f| f.sqrt()).collect()
}
fn main() {
let v = vec![1.0, 4.0, 9.0, 16.0, 25.0];
println!("{:?}", sqrts(&v));
}
Run Code Online (Sandbox Code Playgroud)
编译时出现这种错误,"方法par_iter存在,但不满足以下特征限制:&std::vec::Vec<T> : rayon::par_iter::IntoParallelIterator".如果我使用iter代替par_iter或如果我切换到使用f32或f64代替通用,代码工作正常.
我能做些什么才能par_iter在泛型载体上使用?该IntoParallelIterator特征是否意味着由最终用户实施?我该怎么做呢?
我正在尝试测试是否已使用宏设置了我的依赖项之一的功能cfg!。
下面是一个例子:
my-lib/Cargo.toml
[package]
name = "my-lib"
version = "0.1.0"
edition = "2018"
[features]
some-feature = []
Run Code Online (Sandbox Code Playgroud)
my-lib/lib.rs
[package]
name = "my-lib"
version = "0.1.0"
edition = "2018"
[features]
some-feature = []
Run Code Online (Sandbox Code Playgroud)
my-bin/Cargo.toml
[package]
name = "my-bin"
version = "0.1.0"
edition = "2018"
[dependencies]
my-lib = { path = "../my-lib" }
Run Code Online (Sandbox Code Playgroud)
my-bin/main.rs
pub fn some_function() {
if cfg!(feature = "some-feature") {
println!("SET");
} else {
println!("NOT SET");
}
}
Run Code Online (Sandbox Code Playgroud)
下面显示了不同运行条件下的输出。我预计会出现第二种情况is SET in bin。
> cargo run …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Rust,macro_rules并希望创建一个可以解析HTML语法的宏,并简单地将HTML作为字符串回显.下面的宏大部分都在那里:
macro_rules! html {
() => ("");
($text:tt) => {{
format!("{}", $text)
}};
(<$open:ident>[$($children:tt)*]</$close:ident>$($rest:tt)*) => {{
format!("<{}>{}</{}>{}",
stringify!($open),
html!($($children)*),
stringify!($close),
html!($($rest)*))
}};
}
Run Code Online (Sandbox Code Playgroud)
然后使用宏:
println!("{}",
html!(
<html>[
<head>[
<title>["Some Title"]</title>
]</head>
<body>[
<h1>["This is a header!"]</h1>
]</body>
]</html>
)
);
Run Code Online (Sandbox Code Playgroud)
但是,我真的想删除无关的开合方括号.我尝试这样做如下:
macro_rules! html_test {
() => ("");
($text:tt) => {{
format!("{}", $text)
}};
(<$open:ident>$($children:tt)*</$close:ident>$($rest:tt)*) => {{
format!("<{}>{}</{}>{}",
stringify!($open),
html!($($children)*),
stringify!($close),
html!($($rest)*))
}};
}
Run Code Online (Sandbox Code Playgroud)
但是,当我去使用这个宏时:
println!("{}",
html_test!(
<html>
<head>
<title>"Some Title"</title>
</head>
<body>
<h1>"This is a header!"</h1>
</body>
</html> …Run Code Online (Sandbox Code Playgroud)