Why does Rust prohibit the implementation of existing types?

Like this...

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

... any other?

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

Again, you can extend the type implementation if you define a trait in your box. Why?

+4
source share
1 answer

There are several different arguments pointed out in the following source regarding why it is not possible to implement existing types that are outside the same box,

  • impl . , " Add on Vec<T> concat,..., ... ... mathy [is]. impl upgrade, ... 2."

  • , .. " " 3."

  • . , , , " [] [] , , , " ", " " impl impl, , pull . impl create 4."

  • , impl , impls . " [ ] 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"));
        }
    }
    
+2

Source: https://habr.com/ru/post/1674435/


All Articles