Migwell
Migwell

Reputation: 20127

Issue with a `String` and `thiserror`: `as_dyn_error` exists for reference `&String`, but its trait bounds were not satisfied` in Rust

This is my first attempt to using thiserror in Rust. One of the error types I want to provide is a general string which has a message but no other fields. I've attempted to copy this from the thiserror docs, with the only exception being the use of #[from], so that I can simply return Err(String::from("some string")). The code looks like this:

use thiserror::Error;

#[derive(Error, Debug)]
pub enum Error {
    #[error("{0}")]
    Other(#[from] String)
}

Playground

However, this gives:

   Compiling playground v0.0.1 (/playground)
error[E0599]: the method `as_dyn_error` exists for reference `&String`, but its trait bounds were not satisfied
   --> src/lib.rs:5:13
    |
5   |       #[error("{0}")]
    |               ^^^^^ method cannot be called on `&String` due to unsatisfied trait bounds
    |
    = note: the following trait bounds were not satisfied:
            `String: std::error::Error`
            which is required by `String: AsDynError`
            `&String: std::error::Error`
            which is required by `&String: AsDynError`
            `str: Sized`
            which is required by `str: AsDynError`
            `str: std::error::Error`
            which is required by `str: AsDynError`

For more information about this error, try `rustc --explain E0599`.
error: could not compile `playground` due to previous error

What is the issue here, any how can I resolve it, while keeping the From impl?

Upvotes: 5

Views: 2443

Answers (1)

Netwave
Netwave

Reputation: 42716

The [from] tag is used when your error wraps another error. In this case you do not need it. But you need to actually wrap whatever String with the proper Other constructor:

use thiserror::Error;

#[derive(Error, Debug)]
pub enum Error {
    #[error("{0}")]
    Other(String)
}

fn main() -> Result<(), Error> {
    Err(Error::Other("Hey oh let's go!".to_string()))
}

Playground

Upvotes: 4

Related Questions