Skip to content

String, From and Box<Error> interoperation could be better. #30156

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
michaelsproul opened this issue Dec 2, 2015 · 1 comment
Closed

String, From and Box<Error> interoperation could be better. #30156

michaelsproul opened this issue Dec 2, 2015 · 1 comment

Comments

@michaelsproul
Copy link
Contributor

There's an implementation of From that allows the conversion of a String to a Box<Error + Send + Sync>, but it doesn't quite work when just using Box<Error>.

Code

use std::error::Error;

fn main() {
    // Ok.
    let e1: Box<Error + Send + Sync> = From::from("hello".to_string());
    let e2: Box<Error> = e1;

    // Not ok.
    let e3: Box<Error> = From::from("hello".to_string());

    println!("{:?} {:?}", e2, e3);
}

Compiler Output

michael: ~ $ rustc -V
rustc 1.6.0-nightly (9303055f3 2015-11-19)

michael: ~ $ rustc test.rs 
test.rs:9:26: 9:36 error: the trait `std::error::Error` is not implemented for the type `collections::string::String` [E0277]
test.rs:9     let e3: Box<Error> = From::from("hello".to_string());
                                   ^~~~~~~~~~
test.rs:9:26: 9:36 help: run `rustc --explain E0277` to see a detailed explanation
test.rs:9:26: 9:36 note: required by `core::convert::From::from`
error: aborting due to previous error

The (perhaps subtle) error message is due to the compiler attempting to use the general From<E: Error> implementation for Box<Error>.

Solutions and Workarounds

I was trying to return string errors from a function returning Result<_, Box<Error>> and ended up writing the following:

fn string_error<T>(s: String) -> Result<T, Box<Error>> {
    let err: Box<Error + Send + Sync> = From::from(s);
    Err(err as Box<Error>)
}

This works well, but is really just boilerplate and not obviously suited to inclusion in any crate or library. Other solutions I thought of include:

  • Adding impl From<String> for Box<Error> to the standard library for cases like this.
  • Altering the semantics for trait-resolution on types that parametrise over multiple traits. From what I've read, we don't yet have semantics for general additions of traits, only built-in ones. See E0225.
@alexcrichton
Copy link
Member

This is somewhat intentional on the side of being conservative, but it seems pretty harmless to add.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants