Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yet again: "expected type parameter, found struct" [duplicate]

Tags:

generics

rust

There are already a couple of questions regarding this particular error message. I read them all, but I cannot figure out what the exact problem is that I am facing here, nor how I can fix it.

I have a struct that has a requirement on the argument that is passed in, and I want to provide a few convenience functions for constructing a new instance. Here it comes:

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))
    }
}

The above minimal example gives the following error:

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 might fulfill your needs:
           - .into_inner()

I tried many variations, but I always end up with the same error. Also note that calling S::new with a cursor from somewhere else (e.g. main) works as expected. I know that it has to do with the generic, and so on (from the answers to other similar questions) but: How can I provide such from_* methods along the impl of my struct?

like image 329
Fleshgrinder Avatar asked Apr 13 '26 15:04

Fleshgrinder


1 Answers

The error message is not that far off in this case, I think. Your impl says:

impl<R: Read + Seek> S<R>

so your new function should create a type which is variable in R, but you only supply a fixed type, Cursor<String>. Try this instead:

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 }
    }

}

impl S<Cursor<String>> {
    pub fn from_string(s: String) -> Self {
        S::new(Cursor::new(s))
    }
}
like image 193
Florian Weimer Avatar answered Apr 16 '26 09:04

Florian Weimer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!