简体   繁体   中英

What is the scope of a trait implementation on a type from the standard library in Rust?

The rust book says:

We can also implement Summary on Vec<T> in our aggregator crate, because the trait Summary is local to our aggregator crate.

https://doc.rust-lang.org/book/ch10-02-traits.html#implementing-a-trait-on-a-type

If my package uses another crate from crates.io, like rand , and rand implements a trait on a type in the standard library, like Vec<T> , will my code be able to see those methods?

I know there's a restriction where a trait has to be in scope for you to use its methods. If rand implemented a custom trait on Vec<T> , and I tried to use one of the methods in that trait within my crate, would the compiler tell me that I need to import that trait from rand before using those methods, or would it tell me that the methods don't exist? If it's the former, if I import the trait from rand , can I then use those methods on Vec<T> ?

From my experimentation, if a crate implements a trait on a foreign type, that trait is accessible using the normal rules (that is, in order to call methods of that trait, you must bring it in into scope, but otherwise, nothing special is required). You don't need to do anything else.

For example, consider the crate serde , which provides facilities to serialize and deserialize data. It provides the traits Serialize and Deserialize , which allow data structures to define how they are serialized and deserialized into various formats. Additionally, it provides implementations of those traits for many built-in and std types (see here and here ). I made a quick experiment here , and my code can use those traits without me having to do anything extra (in fact, as you'll see, since I never directly use those traits, I don't even have to bring them into scope).

So, to the best of my knowledge, the answer to your question is yes, your code can use a trait implemented by rand for Vec<T> . All you need to do is import that trait from rand .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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