by DemocracyFTW2 · 2y ago · 0 comments
use jiff::{Timestamp, ToSpan};
fn main() -> Result<(), jiff::Error> {
let time: Timestamp = "2024-07-11T01:14:00Z".parse()?;
I seem to remember Rust does that thing with interfaces instead of classes, is it that? How come I import a library and all of a sudden strings have a `parse()` method that despite its generic name results in a `Timestamp` object? or is it the left-hand side that determines which meaning `str.parse()` should have? What if I have two libraries, one for dates and one for say, Lisp expressions that both augment strings with a `parse()` method? Why use this syntax at all, why not, say, `Timestamp.parse( str )`? I have so many questions.Its return type is generic, and here it's inferred from the left hand side. It's implemented using the `FromStr` trait, and you can equivalently write `Timestamp::from_str(t)`.
You're thinking of the "extension trait" pattern for using traits to add methods to existing types when the trait in scope, but that's not what's going on here. Jiff's `ToSpan` mentioned above is an example of that pattern, though: https://docs.rs/jiff/latest/jiff/trait.ToSpan.html
- let time = Timestamp::parse("2024-07-11T01:14:00Z")?;
- let time: Timestamp = "2024-07-11T01:14:00Z".parse()?;
- let time = "2024-07-11T01:14:00Z".parse::<Timestamp>()?;
You’re free to choose whatever you prefer, although the compiler needs to be able to infer the type of time. If it can’t, it’ll let you know.
So a fourth option is allowed, as long as the subsequent lines make the type of time unambiguous.
- let time = "2024-07-11T01:14:00Z".parse()?;
This is a direct consequence of Timestamp implementing the FromStr trait.
There will never be two libraries that clash because of Rust’s orphan rule: you can only implement either a trait which you define on any type, or define a foreign trait on a type which you define, so there’s no way for some random library to also ship an implementation of FromStr for Timestamp
Not being snarky, but I suggest starting by reading at least a little about traits? None of your questions are really about this library - it's just FromStr and an orphan rule.
> `strongman.open( door )` is just that much clearer, flexible and explicit.
Where the strongman came from? Entirely different semantics.
> let time: Timestamp = "2024-07-11T01:14:00Z".parse::<Timestamp>()?;