This test code (playpen):
use std::fmt::{Display, Formatter, Error};
struct MyLocalType;
type MyResult = Result<MyLocalType, String>;
impl Display for MyResult {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
f.write_str("some test string")
}
}
fn main() {
let r: MyResult = Ok(MyLocalType);
println!("{}" , r);
}
Produces this error message:
<anon>:7:1: 11:2 error: the impl does not reference any types defined in this crate; only traits defined in the current crate can be implemented for arbitrary types [E0117]
<anon>:7 impl Display for MyResult {
<anon>:8 fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
<anon>:9 f.write_str("some test string")
<anon>:10 }
<anon>:11 }
This code successfully compiled in the January version of Rust; how can I implement it now?
There's no direct way to solve this for a pure alias like type
.
The code is the same as
impl Display for Result<MyLocalType, String>
and the compiler can't ensure that there will be no conflicting implementations in other crates (aka, can't ensure that the implementation is 'coherent'). Being able to do it is definitely useful sometimes, but it was unfortunately a bug that the compiler accepted it before.
Solutions include:
Result
, e.g. struct MyResult(Result<MyLocalType, String>);
,enum MyResult { Ok(MyType), Err(String) }
,println!("{}", Wrapper(r));
instead of println!("{}", r);
.Both of these make MyResult
a local type, and so the impl
then should be legal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With