3 ms·
Are you just being snarky or are you actually assuming that is code you'd write?
by Klonoar 4y ago
Are you just being snarky or are you actually assuming that is code you'd write?
- alcover 4y agoBeing gently snarky. The code is from the article and frankly looks an irradiated still-born.
- tialaramex 4y agoI find Rust way more readable than the similarly powerful C++. fn f<T: Into<MyType>>(t: T) -> MyType { t.into() } We've got an introducer keyword 'fn'. We're defining a fn function named f. Cool, in C++ I might have gotten a long way before I found out what the function's name was. Hopefully this is an example name, obviously don't really just name your functions "f" <T: Into<MyType>> means there's a type parameter here, our f function can work with different types, T, however, it also constrains the type parameter by saying it must implement a Trait, named Into<MyType>. In Rust we're allowed to also write these type constraints separately, and if they're complicated it's bad style to put them here, but this constraint was very simple. (t: T) means the f function takes a single parameter, named t (again, please give things better names in real life people) of type T, that T is the one we just met, it's some type which implements Into<MyType> -> MyType means the function returns a value of MyType. { t.into() } is the entire function definition. This function just calls the method into() on the parameter t. How does it know it can call into() ? If you're a C++ programmer you might assume it's just duck typed, C++ just does text replacement here which is how you get those horrible multi-page scrolling template errors, but nope, in Rust it knew because the thing we know about t is that its type is T, and the only thing we know about T is that it implements Into<MyType> which is a trait with exactly this into() method defined, where the return type of that into() method will be MyType. We actually didn't know how to do almost anything else with t except call into()