Can not implement trait from another crate for generic type from another crate parameterized with local type

后端 未结 1 501
感动是毒
感动是毒 2021-01-05 16:00

This test code (playpen):

use std::fmt::{Display, Formatter, Error};

struct MyLocalType;

type MyResult = Result;

impl Display f         


        
1条回答
  •  伪装坚强ぢ
    2021-01-05 16:38

    There's no direct way to solve this for a pure alias like type.

    The code is the same as

    impl Display for Result
    

    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:

    • defining a proper wrapper type for Result, e.g. struct MyResult(Result);,
    • defining your own enum: enum MyResult { Ok(MyType), Err(String) },
    • define a wrapper type, but only use it when printing, i.e. write println!("{}", Wrapper(r)); instead of println!("{}", r);.

    Both of these make MyResult a local type, and so the impl then should be legal.

    0 讨论(0)
提交回复
热议问题