Rust understanding From trait [duplicate]

空扰寡人 提交于 2019-12-11 18:05:05

问题


I'm trying to understand how the From trait works. I've seen it used a lot when you want to override an error from a library with your own custom error. I tried to come up with a contrived example to see that property in action:

struct Blah{

}

impl From<i32> for Blah {

    fn from(b:i32) -> Blah {
        return Blah {

        };
    }

}

fn main() {

}

fn get_result() -> Result<Blah, Box<dyn std::error::Error>> {

    return Ok(20);
}

Error:

return Ok(20);
   |               ^^ expected struct `Blah`, found integer
   |
   = note: expected type `Blah`
              found type `{integer}`

I understand the error, but I don't understand why the integer isn't being implicity converted into a Blah, given that I have implemented From<i32> for Blah

来源:https://stackoverflow.com/questions/57853235/rust-understanding-from-trait

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!