-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Proposal: Require explicit cast between different type aliases even if they are compatible #18991
Comments
Related (duplicate?): #1595 |
Type aliases in Zig are far more frequently used as just that: aliases. You'll see things like What you really seem to want is some method to create distinct types, as in the proposal linked above (#1595). When you're working with integers, there is a convention for this today: using a non-exhuastive enum. const MyId = enum(u64) {
// This marks the enum as "nonexhuastive", so that every `u64` can be used as an
// enum variant, even if we don't have an explicit name for it.
_,
}; This solves the problem for the most common class of type (note that |
Currently, the Zig compiler does not fail when type aliases are used interchangeably, and I argue it should. I will motivate my proposal with a concrete example.
In the code below, although
OwnerId
andPetId
are technically the same thing (both areu64
), they semantically represent different things (an owner and a pet) which are not interchangeable. Functions that acceptOwnerId
should not be called withPetId
and vice-versa, even though the underlying parameter types are perfectly compatible.Currently, the Zig compiler sees no issue with this, and will compile without errors or warnings.
My proposal is to make the implicit cast of
famous_pet
toOwnerId
raise a compilation error like soIn case the user really knows what they are doing and are OK with passing a
PetId
into anOwnerId
, they should tell the compiler of their intentions with a@as(OwnerId, famous_pet)
. This cast would result in a no-op and the code would work as normal.I believe this addition would be especially useful for large applications with lots of different entities (users, accounts, repositories, teams, you name it) which relate to each other and make these kinds of mistakes more likely.
The text was updated successfully, but these errors were encountered: