相关疑难解决方法(0)

如何从函数返回Filter迭代器?

我想要这样的东西:

fn filter_one<'a, T: Int>(input: &'a Vec<T>) -> ??? {
    input.iter().filter(|&x| x == Int::one())
}
Run Code Online (Sandbox Code Playgroud)

该函数的返回类型是什么?(我想要返回Iterator)

(我希望这不是太明显,我现在已经尝试了半个小时而且开始感到沮丧:p)

编辑:

我试着按照这里 =>游戏围栏链接的说明操作

编译器给我以下错误:

<anon>:5:1: 7:2 error: the trait `core::kinds::Sized` is not implemented for the type `for<'r> core::ops::Fn(&'r T) -> bool + 'a`
<anon>:5 fn filter_one<'a, T: Int>(input: &'a Vec<T>) -> Filter<&T, Iter<'a, T>, Fn(&T) -> bool>{
<anon>:6     input.iter().filter(|&x| x == Int::one())
<anon>:7 }
<anon>:5:1: 7:2 note: required by `core::iter::Filter`
<anon>:5 fn filter_one<'a, T: Int>(input: &'a Vec<T>) -> Filter<&T, Iter<'a, …
Run Code Online (Sandbox Code Playgroud)

generics iterator rust

25
推荐指数
2
解决办法
3093
查看次数

如何从方法返回特征实例?

我正在尝试创建一个返回Shader特征实例的函数.这是我极为简化的代码:

trait Shader {}

struct MyShader;
impl Shader for MyShader {}

struct GraphicsContext;

impl GraphicsContext {
    fn create_shader(&self) -> Shader {
        let shader = MyShader;
        shader
    }
}

fn main() {}
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

error[E0277]: the trait bound `Shader + 'static: std::marker::Sized` is not satisfied
  --> src/main.rs:10:32
   |
10 |     fn create_shader(&self) -> Shader {
   |                                ^^^^^^ `Shader + 'static` does not have a constant size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `Shader …
Run Code Online (Sandbox Code Playgroud)

traits rust

25
推荐指数
2
解决办法
1万
查看次数

为什么特质不能自我构建?

这段代码给我一个编译错误:

trait IBoo {
    fn new() -> Box<IBoo>;
}
Run Code Online (Sandbox Code Playgroud)

虽然此代码编译没有任何错误:

trait IBoo {
    //fn new() -> Box<IBoo>;
}

trait IFoo {
    fn new() -> Box<IBoo>;
}
Run Code Online (Sandbox Code Playgroud)
  1. 为什么第一个不能编译?rustc --explain E0038不直接暗示我为什么不可能.
  2. 是否可以在一个界面(特征)中组合构造和方法?

rust

13
推荐指数
2
解决办法
3255
查看次数

是否可以在特征中使用构造函数?

我试图在特征中找到构造函数的例子,但运气不好.这是Rust的惯用之处吗?

trait A {
    fn new() -> A;
}

struct B;
impl A for B {
    fn new() -> B {
        B
    }
}

fn main() {
    println!("message")
}
Run Code Online (Sandbox Code Playgroud)
<anon>:7:8: 9:9 error: method `new` has an incompatible type for trait: expected trait A, found struct `B` [E0053]
<anon>:7        fn new() -> B {
<anon>:8          B
<anon>:9        }
<anon>:7:8: 9:9 help: see the detailed explanation for E0053
error: aborting due to previous error
playpen: application terminated with error code 101
Run Code Online (Sandbox Code Playgroud)

转换它会返回core …

rust

8
推荐指数
1
解决办法
2391
查看次数

是否可以在特征中声明类型别名?

现有语法允许我们为关联类型编写默认值:

trait Foo {
    type Bar = i32;
}
Run Code Online (Sandbox Code Playgroud)

我想要类似 C++ 的东西:

trait Foo {
    typedef int Bar;
}
Run Code Online (Sandbox Code Playgroud)

这不是有效的 Rust 代码,但试图表明我的意图:

trait Foo<T> {
    trait Trait = Into<T> + /* 10 other traits dependent on T */;
    
    fn foo(x: Type) -> Trait;
}
Run Code Online (Sandbox Code Playgroud)

traits rust type-alias

6
推荐指数
1
解决办法
3224
查看次数

我可以根据闭包指定迭代器的类型吗?

我编写了一个函数来迭代二维网格中单元格的邻居:

pub fn neighbours(
    (width, height): (usize, usize),
    (x, y): (usize, usize),
) -> impl Iterator<Item = (usize, usize)> {
    [(-1, 0), (1, 0), (0, -1), (0, 1)]
        .iter()
        .map(move |(dx, dy)| (x as i64 + dx, y as i64 + dy))
        .filter(move |&(nx, ny)| 0 <= ny && ny < height as i64 && 0 <= nx && nx < width as i64)
        .map(|(nx, ny)| (nx as usize, ny as usize))
}
Run Code Online (Sandbox Code Playgroud)

请注意,它返回一个impl Iterator<Item = (usize, usize)>. …

closures types rust

6
推荐指数
1
解决办法
389
查看次数

当用作函数的参数类型或返回类型时,`impl`是什么意思?

我读了这段代码:

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++中实现它?

rust

5
推荐指数
2
解决办法
521
查看次数

如何在结构中存储类型为“impl Trait”的变量?

这有效:

let fut = Arc::new(Mutex::new(Box::pin(async { 1 })));

let mut conn_futures = BTreeMap::new(); // implicitly typed
conn_futures.insert(123, fut);
if let Some(fut) = conn_futures.get_mut(&123) {
   let fut = fut.clone();
   self.pool.spawn(async move {
        let mut fut = fut.try_lock().unwrap();
        (&mut *fut).await;
    });
};
Run Code Online (Sandbox Code Playgroud)

我如何在结构中写同样的东西;是什么类型的conn_futures?根据编译器的说法,它是BTreeMap<i32, impl Future>,但无法将其写入结构中:

struct Foo {
    conn_futures: BTreeMap<i32, impl Future>, // impl not allow in this position
}
Run Code Online (Sandbox Code Playgroud)

我试过这个:

use futures::{executor::LocalPool, lock::Mutex, task::SpawnExt, Future}; // 0.3.1
use std::{collections::BTreeMap, pin::Pin, sync::Arc};

struct Foo {
    conn_futures: BTreeMap<i32, Arc<Mutex<Pin<Box<dyn …
Run Code Online (Sandbox Code Playgroud)

future rust

4
推荐指数
1
解决办法
2200
查看次数

标签 统计

rust ×8

traits ×2

closures ×1

future ×1

generics ×1

iterator ×1

type-alias ×1

types ×1