6 ms·
fn f<T: Into<MyType>>(t: T) -> MyType { t.into() } Picturing a group of nuclear-winter survivors trying to restart a coal plant. Found the control room. Inside
by alcover 4y ago
fn f<T: Into<MyType>>(t: T) -> MyType { t.into() }
Picturing a group of nuclear-winter survivors trying to restart a coal plant. Found the control room. Inside, a working diesel generator, a computer and a Rust manual.
- nequo 4y agoThe binary would most likely work correctly so they could restart the coal plant, and read the Rust manual later to understand the source code.
- badrequest 4y agoAnd who wouldn't want to run a binary that compiles to some unknown effect after a devastating apocalypse?
- alcover 4y agoI agree my fiction is leaky, but it sounds like a nice prompt.
- Klonoar 4y agoAre 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()