Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> Is Rust like Ruby in that devs and library authors can add methods to and redefine built-ins?

It's closer to refinements than monkey-patching, that is, you can, but you must bring the trait into scope for it to work.

> And that merely including a library can alter the definition of those objects everywhere in your project's code?

No, based on the above rule. We don't want that.



Which line is including the trait to allow the functionality in this example? (taken from https://tokio.rs/)


In this case, it's https://github.com/rust-lang/rust/blob/b9637f79e261d0b90d23b...

So, specifically. Rust has "traits", which, for these purposes, work like Ruby modules. But. Rust has "coherence rules." That is,

  You can only implement a trait for a type if you defined either the trait, or the type, or both.
So, because libstd (well, Rust itself, but you get the idea) all three of FromStr, &str, and SocketAddr, it's allowed to do this. You, in your own package, could not define this, since you wouldn't have defined any of them.

In tokio-core, they bring SocketAddr into scope: https://docs.rs/tokio-core/0.1.3/src/tokio_core/net/tcp.rs.h...

However, I was thinking of a slightly different case when I said that, which is methods. That is, you couldn't call methods unless they've had their traits brought into scope. But parse isn't on a trait; it's defined on `str` itself. In that definition, it also has to bring FromStr into scope.

So basically, this is very muddled by the fact that this particular example uses the standard library heavily, which already implicitly brings a lot of things (like &str) into scope for you. External packages don't have that.


> So, because libstd (well, Rust itself, but you get the idea) all three of FromStr, &str, and SocketAddr, it's allowed to do this. You, in your own package, could not define this, since you wouldn't have defined any of them.

It's unclear to me what you're saying here. It's true that you can't make an inherent method `parse` on str like the one being called here, it's also true that one couldn't implement FromStr for SocketAddr in an external package, but one can create a custom generic function that uses FromStr and have that generic type be SocketAddr for some call sites. Of course, if this function wanted to have the syntax of a method call on str, it would have to be defined in a trait that users then import.

> In tokio-core, they bring SocketAddr into scope: https://docs.rs/tokio-core/0.1.3/src/tokio_core/net/tcp.rs.h....

To be clear, this isn't necessary for calling methods---including inherent methods on SocketAddr---unlike the methods in a trait. The only reason to do this is that it lets one abbreviate the name: "SocketAddr" instead of "::std::net::SocketAddr".


Ah, duh, good call.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: