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


#1

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


#2

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


#3

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);

#4

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).


#5

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?


#6

I can suggest you reading this:


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”.


#7

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


#8

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


#9

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”.


#10

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.