logoalt Hacker News

i2talics • today at 4:14 AM • 0 replies • view on HN

The author is going towards the right solution but their solution has things flipped, and the result feels like a hack. What I would suggest is instead of implementing a trait with a magic type parameter, you should instead solve this by providing an object that dispatches the trait method rather than dispatching it from the target type.

That is, instead of "trait ToJson { fn to_json(&self) -> Json }" you should have "trait JsonSerializer<T> { fn to_json(&self, what: &T) -> Json }". Now we can implement "impl JsonSerializer<Date> for ISO8601" and "impl JsonSerializer<Date> for TimestampSeconds".

If this seems a little wordy, realize that actually we've just reimplemented Rust's closures as our own custom trait. So we could just use closures: "JsonSerializer<T>" is the same thing as the trait "Fn(&T) -> Json". This is exactly what serde features, as you can pass in a serializer function rather than using the type itself to look up the behavior[1].

One other place this commonly comes up for me is in comparisons. Some types, like strings, don't have a single universal way to compare them. This means that Ord is insufficient. The solution is to have a "comparator" trait that provides the ordering. Again, this could also just be a closure with two arguments.

[1]: https://serde.rs/field-attrs.html#serialize_with