2017-11-10 41 views
0

關於這個特定的錯誤信息已經有幾個問題。我把它們全部讀了一遍,但我無法弄清楚我在這裏面對的確切問題是什麼,也不知道我該如何解決它。又一次:「期望的類型參數,找到結構」

我有一個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)) 
    } 
} 

上面的小例子,提供了以下錯誤:

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

我嘗試了許多變化,但我總是相同的錯誤結束。還要注意,調用S::new並在其他地方使用遊標(例如main)會按預期工作。我知道它與泛型等有關(來自對其他類似問題的答案),但是:如何在我的structimpl沿途提供這樣的from_*方法?

回答

4

在這種情況下,我認爲錯誤信息並不遙遠。您impl說:

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

所以你new功能應該創建一個類型,是在R變量,但只提供一個固定的類型,Cursor<String>。試試這個:

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

現在一切都開始有意義,非常感謝。 =) – Fleshgrinder

相關問題