Alexito's World

A world of coding 💻, by Alejandro Martinez

Rust Traits restriction

From Rust Traits page:

There’s one more restriction on implementing traits: either the trait, or the type you’re writing the impl for, must be defined by you. So, we could implement the HasArea type for i32, because HasArea is in our code. But if we tried to implement ToString, a trait provided by Rust, for i32, we could not, because neither the trait nor the type are in our code.

I’m curious to know why Rust has this restriction. And, if it’s a technical limitation, how Swift overcomes it.

Because in Swift you can to it:

extension Int: SequenceType { public func generate() -> AnyGenerator { var current = self return anyGenerator { guard current >= 0 else { return nil } return current-- } } } *Is a dumb example, but it works.* ***Update**: Aaron Turon from the Rust team has answered:*

If you liked this article please consider supporting me