Trait objects only provide access to the trait interface

When we use a trait object, the only parts of the original object that we have access to are the parts that are defined by the trait. That means that we can call the forward and reverse functions, but we have no direct access to the blocks member of the Forward type, or the slight member of the Turn type, and so on. A trait object only gives us the things that are guaranteed to be present in any of the data types it can represent: the trait's own interface.

That makes sense, when we think about it. What's the computer supposed to do if we ask it to access slight, but the value we're looking at is actually a Forward type? Some languages would let us try and just crash the program if we tried it at the wrong time, while others would spend time while the program was running checking things like that and catching errors as they happen, but neither of those is the Rust way. In Rust, if the compiler can't be sure that something is okay, it's usually an error.

That means that a trait's interface needs to be complete, in the sense that anything you can reasonably do with a data value that has the trait should be part of the interface. That's not a burden most of the time. After all, why would we want it any other way?

We've been using the word interface a lot. Some languages, such as Java, have a feature that's actually called interface, and yes, Rust traits are similar to Java interfaces, although not identical.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.93.64