I think the dot syntax for enums of Swift is useful for removing duplicate codes. It seems there are not discussions about this yet.
As for a Swift example, please see here or below.
enum CompassPoint {
case north
case south
case east
case west
}
var directionToHead = CompassPoint.west // explicit when declared
directionToHead = .south // inferred when having context
switch directionToHead {
case .north:
print("Lots of planets have a north")
case .south:
print("Watch out for penguins")
case .east:
print("Where the sun rises")
case .west:
print("Where the skies are blue")
}
As Rust uses ::
instead of .
to access a value in an enum, I am expecting something like
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
let mut coin = Coin::Nickel;
coin = ::Penny;
match coin {
::Penny => 1,
::Nickel => 5,
::Dime => 10,
::Quarter => 25,
};
The use case that needs such a syntax sugar is somewhere enums are frequently used. I think you can see the benefit from the above match
example.
For another example, when I worked with wgpu
APIs, there are a lot Descriptor
types, which are used to configure the specs needed to create another complex struct. They used a lot of enums, and worst, the enums sometimes lie deep in the API hierarchy. See the code below:
let sampler = device.create_sampler(&SamplerDescriptor {
address_mode_u: AddressMode::ClampToEdge,
address_mode_v: AddressMode::ClampToEdge,
address_mode_w: AddressMode::ClampToEdge,
mag_filter: FilterMode::Linear,
min_filter: FilterMode::Linear,
mipmap_filter: FilterMode::Nearest,
compare: Some(CompareFunction::LessEqual),
lod_min_clamp: -100.0,
lod_max_clamp: 100.0,
..Default::default()
});
From the attribute names, we can see the meaning and infer a specific enum should be used, so something like below is straightforward to me, although : ::
looks not elegant. With such a syntax sugar, we don't need to peak into the doc of this struct and find out which enum to use, which should give some efficiency boost.
let sampler = device.create_sampler(&SamplerDescriptor {
address_mode_u: ::ClampToEdge,
address_mode_v: ::ClampToEdge,
address_mode_w: ::ClampToEdge,
mag_filter: ::Linear,
min_filter: ::Linear,
mipmap_filter: ::Nearest,
compare: Some(::LessEqual),
lod_min_clamp: -100.0,
lod_max_clamp: 100.0,
..Default::default() // probably `::default()` as well?
});
Adding this syntax sugar should not break the existing code, but it affects backward compatibility of code.
Although we can do something like use a::b::c::SomeEnum::*
as a quick fix, but this has a side effect that brings unnecessary imports into a scope, and we cannot easily handle some edge cases where two imported enums have enum values of the same names.
So, it seems reasonable to me. But, does the community have some strong reasons not to do so?
Edit: As pointed out by @steffahn, ::
is used in Rust, but an alternative seems good.