Resolving trait implementation conflicts

时光毁灭记忆、已成空白 提交于 2019-12-05 09:00:46

The problem here is the (current) compiler does not register that Complex<T> does not implement Float. Imagine if Complex did implement Float: either there would have to be some way to decide which impl to use, or the overlapping code would have to be outlawed... but what if someone only adds the impl<T> Float for Complex<T> in some other crate the compiler doesn't know about?

This last point is key: unlike Haskell, Rust's design allows this code to be perfectly OK without any risk, all because Rust differs in how it handles the last point. If you are in a crate that can see a type Type and a trait Trait, then you know for 100% sure if Type implements Trait: Rust doesn't have Haskell's open world assumption, as you can only write impl Trait for Type if either Trait or Type lie in the current crate (compilation unit), that is, you can't have orphan instances, where someone implements Float for Complex<T> in some distant crate.

RFC 24 (that Chris links to) recognises this, allowing these generic implementations to coexist with more specific ones, as long as the implementations are guaranteed to not overlap.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!