Skip to content

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

Closed
@michaelsproul

Description

@michaelsproul

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions