简体   繁体   English

如何 select 在 Rust 中正确实现特征?

[英]How to select the proper trait implementation in Rust?

I have a trait that expects either reqwest::Response or Vec as argument, only to throw them in a select::document::Document .我有一个特征,期望reqwest::ResponseVec作为参数,只是将它们扔进 select::document::Document To come to that end, I need to somehow get an implementation of io::Read for Vec<u8> in order to use Document::from_read .为此,我需要以某种方式实现io::Read for Vec<u8>以便使用Document::from_read

Here's what I came up with:这是我想出的:

use select::document::Document;
use std::{io::Read, io::Result};

#[derive(Debug)]
pub struct ReadableVec<T>(Vec<T>);

impl Read for ReadableVec<u8> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        println!("Read!");
        let mut r: &[u8] = &self.0[..];
        r.read(buf)                           //< issue is here!!
    }
}

fn main() {
    let buf = ReadableVec(vec![60, 116]);
    let doc = Document::from_read(buf);
    println!("{:?}", doc)
}

My question is: why is r.read(buf) calling the Read implementation of ReadableVec instead of &[u8] , thus making my function to recursively call itself?我的问题是:为什么r.read(buf)调用ReadableVec而不是&[u8]Read实现,从而使我的 function 递归调用自身? The type of r seems very clearly instructed by the line above. r的类型似乎由上面的行指示得很清楚。

PS: if there's a better solution to handle both Vec<u8> and reqwest::Response , it'll be appreciated in the comments; PS:如果有更好的解决方案来处理Vec<u8>reqwest::Response ,评论中将不胜感激; ;) ;)

You can disambiguate by referencing the trait method directly, eg:您可以通过直接引用 trait 方法来消除歧义,例如:

use std::io::Read;

#[derive(Debug)]
pub struct ReadableVec<T>(Vec<T>);

impl Read for ReadableVec<u8> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        println!("Read!");
        Read::read(&mut &self.0[..], buf)
    }
}

fn main() {
    let mut buf = ReadableVec(vec![60, 116]);
    buf.read(&mut []);
}

This is called Universal Function Call Syntax (can't find this chapter in the new book, so I'm linking the first edition).这个叫Universal Function Call Syntax (新书找不到这一章,所以我链接第一版)。

I do not think this is sufficient to make the implementation of Read correct though, as this would only advance the (temporary) slice.我认为这不足以使Read的实现正确,因为这只会推进(临时)切片。 See my comment on Cursor .请参阅我对Cursor的评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM