相关疑难解决方法(0)

返回迭代器(或任何其他特征)的正确方法是什么?

以下Rust代码编译并运行没有任何问题.

fn main() {
    let text = "abc";
    println!("{}", text.split(' ').take(2).count());
}
Run Code Online (Sandbox Code Playgroud)

在那之后,我尝试了类似的东西....但它没有编译

fn main() {
    let text = "word1 word2 word3";
    println!("{}", to_words(text).take(2).count());
}

fn to_words(text: &str) -> &Iterator<Item = &str> {
    &(text.split(' '))
}
Run Code Online (Sandbox Code Playgroud)

主要问题是我不确定函数to_words()应该具有什么返回类型.编译器说:

error[E0599]: no method named `count` found for type `std::iter::Take<std::iter::Iterator<Item=&str>>` in the current scope
 --> src/main.rs:3:43
  |
3 |     println!("{}", to_words(text).take(2).count());
  |                                           ^^^^^
  |
  = note: the method `count` exists but the following trait bounds were not satisfied:
          `std::iter::Iterator<Item=&str> : std::marker::Sized`
          `std::iter::Take<std::iter::Iterator<Item=&str>> …
Run Code Online (Sandbox Code Playgroud)

rust

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

预期的类型参数,找到结构

我遇到了一个问题,并将其简化为以下代码:

trait Logger {}

struct DefaultLogger;

impl Logger for DefaultLogger {}

struct A<L> where L: Logger {
    logger: Box<L>,
}

impl<L> A<L> where L: Logger {
    fn new() -> Self {
        let logger = DefaultLogger;

        A {
            logger: Box::new(logger),
                          // ^^^^^^ Here is the problem
        }
    }
}

fn main() {
    let a = A::new();
}
Run Code Online (Sandbox Code Playgroud)

产生以下错误:

trait Logger {}

struct DefaultLogger;

impl Logger for DefaultLogger {}

struct A<L> where L: Logger {
    logger: Box<L>,
}

impl<L> A<L> where L: …
Run Code Online (Sandbox Code Playgroud)

traits rust

7
推荐指数
1
解决办法
4328
查看次数

如何使用通用方法实现特征?

我正在尝试实现一个包含泛型方法的特征.

trait Trait {
    fn method<T>(&self) -> T;
}

struct Struct;

impl Trait for Struct {
    fn method(&self) -> u8 {
        return 16u8;
    }
}
Run Code Online (Sandbox Code Playgroud)

我明白了:

error[E0049]: method `method` has 0 type parameters but its trait declaration has 1 type parameter
 --> src/lib.rs:8:5
  |
2 |     fn method<T>(&self) -> T;
  |     ------------------------- expected 1 type parameter
...
8 |     fn method(&self) -> u8 {
  |     ^^^^^^^^^^^^^^^^^^^^^^ found 0 type parameters
Run Code Online (Sandbox Code Playgroud)

我该怎么写impl正确的块?

rust

6
推荐指数
2
解决办法
754
查看次数

泛型错误:预期类型参数,找到结构

我开始了一个新项目,我希望在其中尽可能地模块化,这意味着我希望将来能够将某些零件替换为其他零件。traits目前,我有以下代码,这似乎是的完美用法:

mod parser;
mod renderer;
mod renderers;

use parser::MarkParser;
use renderer::MarkRenderer;

struct Rustmark <P: MarkParser, R: MarkRenderer> {
    parser: P,
    renderer: R,
}


impl <P: MarkParser, R: MarkRenderer> Rustmark <P, R> {
    fn new() -> Rustmark <P, R> {
        Rustmark {
            parser: parser::DefaultParser::new(),
            renderer: renderers::HTMLRenderer::new(),
        }
    }

    fn render(&self, input: &str) -> &str {
        self.renderer.render(self.parser.parse(input))
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我遇到了两个错误,主要是这个错误:

错误:类型不匹配:预期Rustmark<P, R>,找到Rustmark<parser::DefaultParser, renderers::html::HTMLRenderer> (预期类型参数,找到结构parser::DefaultParser)[E0308]

还有一些像这样的终身错误:

错误:由于需求冲突,无法推断自动强制的适当寿命

帮助:考虑使用显式的生命周期参数,如下所示:fn parse<'a>(&'a self, input: &'a …

generics traits rust

5
推荐指数
1
解决办法
2601
查看次数

如何使用具有闭包成员的结构制作新的关联函数?

我几乎对为什么该代码不起作用有一个直观的认识,但是我不能完全依靠它。我认为这与新函数每次都有不同的返回类型有关。

为什么会有问题呢?为什么直接创建有效?

struct Struct<T>
where
    T: Fn(&[u8]),
{
    func: T,
}

impl<T> Struct<T>
where
    T: Fn(&[u8]),
{
    fn new() -> Struct<T> {
        // this doesn't work
        Struct { func: |msg| {} }
    }
}

fn main() {
    // this works
    let s = Struct { func: |msg| {} };
}
Run Code Online (Sandbox Code Playgroud)

错误是

struct Struct<T>
where
    T: Fn(&[u8]),
{
    func: T,
}

impl<T> Struct<T>
where
    T: Fn(&[u8]),
{
    fn new() -> Struct<T> {
        // this doesn't work
        Struct { func: |msg| {} …
Run Code Online (Sandbox Code Playgroud)

rust

5
推荐指数
1
解决办法
198
查看次数

为什么 std::iter::Map&lt;I, F&gt; 不能作为 Iterator&lt;Item = I&gt; 返回?

我想将此行的映射部分变成一个函数:

let i: Vec<u32> = (0..=5).map(|x| x * 2).collect();
Run Code Online (Sandbox Code Playgroud)

我编写了这段代码,我认为它是我从原始代码中删除的内容的直接插入:

let j: Vec<u32> = process(0..=5).collect();
Run Code Online (Sandbox Code Playgroud)
fn process<I>(src: I) -> I
where
    I: Iterator<Item = u32>,
{
    src.map(|x| x * 2)
}
Run Code Online (Sandbox Code Playgroud)

我得到这个编译时错误:

error[E0308]: mismatched types
 --> src/lib.rs:5:5
  |
1 | fn process<I>(src: I) -> I
  |            -             - expected `I` because of return type
  |            |
  |            this type parameter
...
5 |     src.map(|x| x * 2)
  |     ^^^^^^^^^^^^^^^^^^ expected type parameter `I`, found struct `std::iter::Map`
  |
  = note: expected …
Run Code Online (Sandbox Code Playgroud)

rust

5
推荐指数
0
解决办法
873
查看次数

Rust泛型/特征:"预期'Foo <B>',发现'Foo <Foo2>'"

我问过类似的早期问题已让我明白是怎么回事引擎盖下,但我仍然不能得到锈做我想做的事情,当谈到泛型编程.这是一些代码:

struct Foo<B: Bar> { bars: Vec<Box<B>> }

struct Foo2;

trait Bar {}

impl Bar for Foo2 {}

impl<B: Bar> Foo<B> {
  fn do_something() -> Foo<B> {
    let foo2:Box<Bar> = box Foo2;
    let mut foo = Foo { bars: vec!(box Foo2) };
    foo.bars.push(box Foo2);
    foo // compiler: *ERROR*
  }
}
Run Code Online (Sandbox Code Playgroud)

错误: expected 'Foo<B>', found 'Foo<Foo2>'

  1. 我怎样才能给编译器一个提示或明确告诉编译器foo(Foo)implements Bar(B: Bar)?
  2. 这是一个错误吗?我应该推迟使用Rust直到它达到1.0?

版: 0.12.0-nightly (4d69696ff 2014-09-24 20:35:52 +0000)


我在@Levans的解决方案中看到的问题:

struct …
Run Code Online (Sandbox Code Playgroud)

rust

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

错误:预期类型参数,发现闭包

我有以下代码:

struct Helper<F1: Fn()> {
    f: F1,
}

struct User<F2: Fn()> {
    h: Helper<F2>,
}

fn new_user<F3: Fn()>() -> User<F3> {
    User {
        // error: expected type parameter, found closure
        h: Helper { f: || {} },
    }
}

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

所以User需要一个Helper<F1>由 指定的 F1 类型User,在这种情况下是由中的闭包new_user。

此代码编译失败与错误expected type parameter, found closure在new_user。至于我已经明白(例如见这个链接),这是因为约束类型参数F3上new_user被调用者指定(或签名也许?),因此,虽然关闭实现Fn()特质,它不能限制类型参数 F3 以匹配闭包的类型。相反,它new_user应该适用于任何给定的F3,而这显然不会。

所以我的问题是:我该如何解决这个问题?有没有表达,我想的任何方式new_user …

generics traits rust

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

又一次:"期望的类型参数,找到结构"

关于此特定错误消息已经有几个问题.我读了所有这些,但我无法弄清楚我面临的确切问题是什么,也不知道如何解决它.

我有一个struct对传入的参数有要求,我想提供一些便利函数来构造一个新实例.它来了:

use std::io::{Cursor, Read, Seek};

pub struct S<R: Read + Seek> {
    p: R,
}

impl<R: Read + Seek> S<R> {
    pub fn new(p: R) -> Self {
        S { p }
    }

    pub fn from_string(s: String) -> Self {
        S::new(Cursor::new(s))
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的最小示例给出以下错误:

error[E0308]: mismatched types
  --> src/main.rs:13:16
   |
13 |         S::new(Cursor::new(s))
   |                ^^^^^^^^^^^^^^ expected type parameter, found struct `std::io::Cursor`
   |
   = note: expected type `R`
              found type `std::io::Cursor<std::string::String>`
   = help: here are some functions which …
Run Code Online (Sandbox Code Playgroud)

generics rust

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

在Rust中使用特征的泛型类型不匹配

我正在使用特征进行矩阵加法.我被通用类型不匹配所困扰.我的代码如下:

use std::{ops, fmt};

#[derive(PartialEq, Debug)]
pub struct Matrix<T> {
    data: Vec<T>,
    row: usize,
    col: usize,
}

impl<T: Copy> Matrix<T> {
    /// Creates a new matrix of `row` rows and `col` columns, and initializes
    /// the matrix with the elements in `values` in row-major order.
    pub fn new(row: usize, col: usize, values: &[T]) -> Matrix<T> {
        Matrix {
            data: values.to_vec(), // make copy and convert &[T] to vector type
            row: row,
            col: col,
        }
    }
}

impl<T: ops::Add<Output = T> …
Run Code Online (Sandbox Code Playgroud)

traits rust

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

Rust泛型:预期<T>找到<Foo>

我正在尝试使用泛型,但我不能很好地掌握该主题,并且我收到此错误:

error: mismatched types:
expected `book::mdbook::MDBook<R>`,
found `book::mdbook::MDBook<renderer::html_handlebars::HtmlHandlebars>`
(expected type parameter,
found struct `renderer::html_handlebars::HtmlHandlebars`) [E0308]
Run Code Online (Sandbox Code Playgroud)

这是相关的代码

pub struct MDBook<R> where R: Renderer {
    title: String,
    author: String,
    config: BookConfig,
    pub content: Vec<BookItem>,
    renderer: R,
}

impl<R> MDBook<R> where R: Renderer {

    pub fn new(path: &PathBuf) -> Self {

        MDBook {
            title: String::from(""),
            author: String::from(""),
            content: vec![],
            config: BookConfig::new()
                        .set_src(path.join("src"))
                        .set_dest(path.join("book")),
            renderer: HtmlHandlebars::new(), // <---- ERROR HERE
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

该Renderer特征目前是空的,实现HtmlHandlebars是

pub struct HtmlHandlebars;

impl Renderer for …
Run Code Online (Sandbox Code Playgroud)

generics traits rust

0
推荐指数
1
解决办法
370
查看次数

标签 统计

rust ×11

traits ×5

generics ×4