impl Traits可以用作函数参数.这个和具有特征约束的泛型函数之间是否存在差异?
trait Foo {}
fn func1(_: impl Foo) {}
fn func2<T: Foo>(_: T) {}
Run Code Online (Sandbox Code Playgroud) 在特质文档中Send,我看到了两者
impl<T> Send for LinkedList<T>
where
T: Send,
Run Code Online (Sandbox Code Playgroud)
和
impl<T: Send> Send for LinkedList<T>
Run Code Online (Sandbox Code Playgroud)
这两种语法有什么区别,如果我impl为自己的特性编写声明,它会如何影响我的代码呢?
例如,我有一个简单的分类器
struct Clf {
x: f64,
}
Run Code Online (Sandbox Code Playgroud)
如果观察值小于x则分类器返回0,如果大于x则分类器返回1.
我现在想要为这个分类器实现call运算符.但是,该函数应该能够将float或vector作为参数.在向量的情况下,输出是0或1的向量,其具有与输入向量相同的大小.它应该像这样工作
let c = Clf { x: 0 };
let v = vec![-1, 0.5, 1];
println!("{}", c(0.5)); // prints 1
println!("{}", c(v)); // prints [0, 1, 1]
Run Code Online (Sandbox Code Playgroud)
我该怎么写呢
impl Fn for Clf {
extern "rust-call" fn call(/*...*/) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下?
pub fn up_to(limit: u64) -> impl Generator<Yield = u64, Return = u64> {
move || {
for x in 0..limit {
yield x;
}
return limit;
}
}
Run Code Online (Sandbox Code Playgroud)
什么impl意思?如何在普通的Rust或C++中实现它?
当我发现以下内容时,我正在阅读关于"扩展"impl Trait的RFC:
相比之下,一个程序员首先学习:
fn take_iter(t: impl Iterator)然后尝试:fn give_iter() -> impl Iterator将会成功,没有任何严格的理解,他们只是从普遍性转变为存在性.
虽然我从逻辑的角度理解普遍与存在的关系,但是第一个是普遍的还是第二个存在的?
How do I implement an apply_n_times function which gets a function f: T -> T and a number n and the result will be a function which applies f ntimes?
E.g. apply_n_times(f, 0) equals |x| x and apply_n_times(f, 3) equals |x| f(f(f(x))).
There is no deeper sense in this function, I just want to implement it for learning reasons.
My current code:
fn apply_n_times<T>(f: Fn(T) -> T, n: i32) -> dyn Fn(T) -> T {
if n < …Run Code Online (Sandbox Code Playgroud)