Why we can't provide FromStr deriving for the strong types?

If we have a strong type with only one field, what disallows us from having a FromStr derived?

Can you expand a bit? I'm not entirely sure what you mean by "strong type with only one argument".

Of course. I thought it is very easy to understand though.

struct A(u64);

This creates a strong type - a tuple struct with one field. What prevents us from having FromStr derived here? Like that:

#[derive(FromStr)]
struct A(u64);

Ok - I suspected you meant this but not sure why you put "strong" there (what’s a weak type in Rust then?).

Anyway, technically it’s probably possible but it’s pretty niche (must have a single field). You may also not want to leak the Err type of the underlying field since that may change (eg the u64 is not public in your example).

This sounds like a job for newtype_derive or derive_more, but neither appear to support FromStr in particular. Maybe you could propose it to them?

2 Likes

I can suggest you reading this:

https://stackoverflow.com/questions/2690544/what-is-the-difference-between-a-strongly-typed-language-and-a-statically-typed

Basically, we call "strong type" such a type, which hides something so that it is impossible to convert from and into the inner type implicitly. It is usually done by hiding the type into another type. That another type is called "strong".

You're taking a rather narrow interpretation of strong typing. It's a characteristic of the type system as a whole, not of a particular type, and Rust's type system is mostly strong. There are only a few implicit type coercions:
https://doc.rust-lang.org/nightly/reference/type-coercions.html#coercion-types

1 Like

I know about everything you have said. Nevertheless the strong type term exists. Are you going to talk about it? :slight_smile:

The canonical term for this in Rust is newtype - if you use that term, most people will understand immediately what you mean; not so much with "strong type".

The thing that newtype does is providing the strong type. However, thank you for noticing that it is not know for the usual rust developer. I should use newtype next time for reaching the help faster.