Strong Type Enforcement for Type Aliases

Hi all,

Background: I am implementing a simple BGP simulation system in rust. I encode both the AS number and the prefix as a usize (I am in very early stages, so I still treat the IP prefix as a simple number). Now, I have several HashMaps to map a prefix to the neighboring AS.

I have defined a type alias for both AsId and Prefix. Now, in my code, I can do the following:

type AsId = usize;
type Prefix = usize;

fn test(as_id: AsId, prefix: Prefix, map: HashMap<Prefix, AsId>) {
    // works:
    map.insert(prefix, as_id);
    // also works, but I would like the compiler to throw an error here:
    map.insert(as_id, prefix);
}

Both insert statements are accepted by the compiler, and no warning is thrown. I guess this is the expected behavior, since both AsId and Prefix are usize. However, I really want that the compiler to warn me when I introduce such bugs. Is there a simple way to tell the compiler to do strong type enforcement for type aliases, without defining a struct and deriving / implementing all traits (copy, eq, into...) maually?

Thanks in advance!

This is intended behavior of type aliases (they're just aliases, not distinct types). You can use the newtype pattern instead.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.