[SOLVED] Use of From Trait in Karol Kuczmarski article "Rust Optional Args"


#1

In Karol’s article, he uses the following code example:

fn maybe_plus_5<T>(x: T) -> i32 where Option<i32>: From<T> {
    Option::from(x).unwrap_or(0) + 5
}

While Karol follows with an improved version using the Into trait. This syntax left me scratching my head.

Specifically, how does the where Option<i32>: From<T> clause work for any arbitrary type T?

I read this as “where type (Option of Int 32) implements trait (From of type T)”–perhaps this interpretation is flawed.

Looking at the docs, Option implements impl<T> From<T> for Option<T>, which I interpret as T must be a single type, therefore where Option<i32>: From<T> really implies that T must always be i32, not some arbitrary type. Is this correct?

The article hints that someone could invoke maybe_plus_5(Some(42)) (and indeed you can with nightly Rust), but Some(42) is Option<i32> and not i32, so I’m struggling to understand how Rust reconciles this disparity. This behavior indicates, IMO, that where Option<i32>: From<T> is equivalent to where Option<i32>: From<Option<i32>>.


#2

You’ve already mentioned impl<T> From<T> for Option<T> which is Option-specific, but in the standard library there is also impl<T> From<T> for T (!), which is a second one that can be used.

So in Option<i32>: From<T> both T = Option<i32> and T = i32 fit, and that’s the purpose of the type parameter in this case, to accept either of those two.