Rust (programming language): Difference between revisions

Content deleted Content added
Types and polymorphism: I think that this paragraph is more beginner friendly and clear.
Types and polymorphism: formatting error
Line 137:
The implementation of Rust generics is similar to the typical implementation of C++ templates: a separate copy of the code is generated for each instantiation. This is called monomorphization and contrasts with the [[type erasure]] scheme typically used in Java and Haskell. Rust's type erasure is also available by using the keyword <code>dyn</code>. The benefit of monomorphization is optimized code for each specific use case; the drawback is increased compile time and size of the resulting binaries.
 
In Rust user defined types are created with the <code>struct<\/code> keyword. These types usually contains fields of data like objects or classes in other languages. The <code>impl</code> keyword can define methods for the struct (data and function are defined separately in a struct) or implement a [[Trait (computer programming)|trait]] for the structure. A trait is a contract that a structure has certain required methods implemented. Traits are used to restrict generic parameters and because traits can provide a struct with more methods than the user defined. For example, the trait Iterator requires that the <code>next</code> method be defined for the type. Once the <code>next</code> method is defined the trait provides common functional helper methods over the iterator like map or filter.
 
The object system within Rust is based around implementations, [[Trait (computer programming)|traits]] and structured types. Implementations fulfill a role similar to that of classes within other languages and are defined with the keyword <code>impl</code>. Traits provide inheritance and polymorphism; they allow [[Method (computer programming)|methods]] to be defined and [[Mixin|mixed in]] to implementations. Structured types are used to define fields. Implementations and traits cannot define fields themselves, and only traits can provide inheritance. Among other benefits, this prevents the [[diamond problem]] of [[multiple inheritance]], as in C++. In other words, Rust supports interface inheritance but replaces implementation inheritance with [[Object composition|composition]]; see [[composition over inheritance]].