这个测试代码(围栏):
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);
}
Run Code Online (Sandbox Code Playgroud)
生成此错误消息:
<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 }
Run Code Online (Sandbox Code Playgroud)
此代码在1月版的Rust中成功编译; 我现在该怎么办呢?
对于像这样的纯别名,没有直接的方法可以解决这个问题type.
代码与.相同
impl Display for Result<MyLocalType, String>
Run Code Online (Sandbox Code Playgroud)
并且编译器无法确保在其他包中没有冲突的实现(也就是说,不能确保实现是'连贯').能够做到这一点肯定是有用的,但遗憾的是编译器之前接受它的错误.
方案包括:
Result,例如struct MyResult(Result<MyLocalType, String>);,enum MyResult { Ok(MyType), Err(String) },println!("{}", Wrapper(r));而不是println!("{}", r);.这两个都是MyResult本地类型,所以impl那时应该是合法的.