简体   繁体   English

为什么Rust禁止实现现有类型?

[英]Why does Rust forbid implementations of existing types?

How is this... 这怎么样...

impl String {
    fn foo(&self) {
        //...
    }
}

...any different to this? ......这有什么不同吗?

fn foo(s: &String) {
    //...
}

Then again, it is possible to extend the type implementation if you define a trait in your crate. 然后,如果在包中定义特征,则可以扩展类型实现。 Why? 为什么?

There are several different arguments as indicated by the following source as to why one is unable to implement existing types that are outside of one's crate. 以下来源指出了几个不同的参数,说明为什么一个人无法实现一个箱子之外的现有类型。

  • Local impl can be broken by future implementations. 未来的实现可以打破本地impl。 For example, consider "you've locally defined Add on Vec<T> as a concat operator, ... , and then ... after years of debate ... some mathy operation [is] to be performed instead. If you delete your impl and upgrade, your code will be ... broken 2 ." 例如,考虑“你已经在本地定义了添加Vec<T>作为一个连接运算符,......,然后......经过多年的辩论......一些糟糕的操作[是]要执行。如果你删除你的impl和升级,你的代码将被破坏2.

  • The readability of the code will also be affected by this change, that is, it could make the "value of that reading far more transient 3 ." 代码的可读性也会受到这种变化的影响,也就是说,它可能使“读取的值更加短暂3”

  • There is also a security concern. 还存在安全问题。 Consider the following scenario that would be technically possible if this were allowed, that is, "an attacker [could] find a change in an impl in [some] library, a call site in an application they wish to backdoor, and send a "refactoring" pull request that "accidentally" replaces the new impl with the old impl so as to create a vulnerability, but their pull can reference the old code from the library. And they can embed the hostile impl into a macro in yet another create 4 ." 考虑以下场景,如果允许这样做,技术上是可行的,即“攻击者[可以]找到[某些]库中的impl,他们希望后门的应用程序中的调用站点发送更改,并发送”重构“拉请求”意外“用旧impl替换新impl以创建漏洞,但是他们的拉可以引用库中的旧代码。并且他们可以将恶意impl嵌入到另一个创建中的宏4中 “。

  • Assuming the case that the local impl would be the preferred implementation if local impls were allowed. 假设如果允许本地impl,则本地impl将是首选实现。 This would "would violate the coherence property [that is currently being maintained] 5 ." 这将“违反一致性财产[目前正在维持] 5。 This point can be further clarified through what is called the 'HashTable' problem 5 . 通过所谓的“HashTable”问题5可以进一步阐明这一点。

     mod foo { impl Hash for i32 { ... } fn f(mut table: HashMap<i32, &'static str>) { table.insert(0, "hello"); ::bar::f(&table); } } mod bar { impl Hash for i32 { ... } fn f(table: &HashMap<i32, &'static str>) { assert_eq!(table.get(0), Some("hello")); } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM