为字段创建一个具有通用特征的结构.预期的 struct<trait>找到了实现上述特征的结构体&lt;类型&gt; [英] Creating a struct with a generic trait for field. Expected struct&lt;trait&gt; found struct&lt;type that implements said trait&gt;

查看:31
本文介绍了为字段创建一个具有通用特征的结构.预期的 struct<trait>找到了实现上述特征的结构体&lt;类型&gt;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个具有使用 Write 特性的 BufWriter 的结构,以便该结构可以有一个缓冲写入器,它可以是任何实现该特征:FileStream 等.但我的函数中存在一个问题,该问题创建的结构说我有 不匹配的类型.这是具有相同问题的示例代码.

I'm trying to create a struct that has a BufWriter that uses the Write trait, so that this struct could have a buffered writer that can be anything that implements that trait: File, Stream, etc. But I'm having an issue in my function that creates the struct saying that I have mismatched types. Here is an example code with the same issue.

use std::fs::File;
use std::io::{BufWriter, Write};

pub struct BufWriterStruct<W: Write> {
    pub writer: Option<BufWriter<W>>,
}

impl <W: Write>BufWriterStruct<W> {
    pub fn new(filename: &str) -> BufWriterStruct<W> {
        BufWriterStruct {
            writer: Some(BufWriter::new(File::create(filename).unwrap())),
        }
    }
}

fn main() {
    let tmp = BufWriterStruct::new("tmp.txt");
}

游乐场

有错误

error: mismatched types:
 expected `BufWriterStruct<W>`,
    found `BufWriterStruct<std::fs::File>`

如果我改为更改我的 new 函数以采用实现 Write 特性的参数并在创建 BufWriter 时使用它,它会起作用很好.

If instead I change my new function to instead take a parameter that implements the Write trait and use that when creating BufWriter, it works fine.

我觉得前者应该可以做到.

I feel like the former should be possible to do somehow.

推荐答案

您的错误在于混合了泛型和特定:

Your error is in mixing generic and specific:

impl <W: Write>BufWriterStruct<W> {
    pub fn new(filename: &str) -> BufWriterStruct<W> {
        BufWriterStruct {
            writer: Some(BufWriter::new(File::create(filename).unwrap())),
        }
    }
}

在这里,您的 BufWriter 实例应该接受一个 W:Write,这是由调用者决定的,但该函数实际上创建了一个文件.

Here, your instance of BufWriter should accept a W: Write, which is decided by the caller, yet the function actually creates a File.

让调用者决定:

impl <W: Write> BufWriterStruct<W> {
    pub fn new(writer: W) -> BufWriterStruct<W> {
        BufWriterStruct {
            writer: Some(BufWriter::new(writer)),
        }
    }
}

当然,这会稍微改变调用:

Of course, this will change invocation a bit:

fn main() {
    let tmp = BufWriterStruct::new(File::create("tmp.txt").unwrap());
}

然后它会起作用.

这篇关于为字段创建一个具有通用特征的结构.预期的 struct<trait>找到了实现上述特征的结构体&lt;类型&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆