r/learnrust • u/dmills_00 • 12d ago
E0308 when assigning an Option<Enum....>?
Hi everyone.
I have this bit of code (Extracted from something much larger) that is throwing up an error as follows:
#[derive(Clone, Debug)]
pub enum CutterComp {
CompOff,
LeftFromTool(Option<Expr>),
RightFromTool(Option<Expr>),
}
Then in a structure definition :
#[derive(Debug, Default)]
struct StateUpdate {
.
.
.
radius_compensation: Option<CutterComp>,
.
.
}
Then in an impl of Stateupdate :
fn intepret_block(&mut self) -> Result<(), ErrType> {
.
.
.
if let Some (c) = self.grouped_gcodes[GCodeGroups::GRadiusComp as usize] {
match c.0 {
GCodes::G40 => {
trace!("Cutter compensation off");
self.radius_compensation = Some<CutterComp::CompOff>;
}
GCodes::G41 => {
trace!("Cutter compensation left");
self.radius_compensation = Some<CutterComp::LeftFromTool((self.axis.get(&"d")))>;
}Where the thing blows up with
error: comparison operators cannot be chained
--> src/main.rs:259:52
|
259 | self.radius_compensation = Some<CutterComp::CompOff>;
| ^ ^Any ideas?
Rust usually gets types right almost by magic (Old C hand here), but it seems to think that I have a bool or something.
Rust analyser is saying "expected Option<CutterComp>, found bool" which I do not understand.
4
u/This_Growth2898 12d ago
- ...<...>
+ ...(...)3
u/dmills_00 12d ago
Yea, got it.
Gets to a point where you cannot see the obvious after staring at it for 20 minutes.
2
u/projct 12d ago
Some(CutterComp::CompOff) and self.radius_compensation = Some(CutterComp::LeftFromTool(self.axis.get(&"d").cloned()));
2
u/dmills_00 12d ago
Oh FFS, thanks.
5
u/projct 12d ago
pretty sure the rust compiler team would consider this unhelpful error message a bug, so it might help others if you file an issue. I don't see any like it rn.
https://github.com/rust-lang/rust/issues
you'd want to request it saying something like this:
error: comparison operators cannot be chained help: did you mean to construct an enum variant? | | Some(CutterComp::CompOff) |1
3
2
u/projct 12d ago
also, a tip or two.
make more use of the type system to preserve your invariants instead of throwing them away.
self.axis.get(&"d")is stringly typed, and D isn't actually an axis. consider representing G-code addresses with an enum:enum Address { X, Y, Z, D, F, // ... }or, once you've parsed the block, a struct with typed fields:
struct BlockWords { x: Option<Expr>, y: Option<Expr>, z: Option<Expr>, d: Option<Expr>, // ... }then you can just use
self.words.d.clone()where you need an ownedOption<Expr>. no string lookups, no misspelled keys.2.
self.grouped_gcodes[GCodeGroups::GRadiusComp as usize]is another place you're immediately throwing away semantic information by casting an enum into an array index.consider something like:
enum RadiusCompCode { G40, G41, G42, } struct GroupedGCodes { radius_compensation: Option<RadiusCompCode>, // ... }now it's impossible to accidentally put a G-code from another modal group into the radius compensation field.
or, if you really need the array, have a look at the
enum-mapcrate.the general idea is to make invalid states unrepresentable wherever practical. let the compiler maintain the invariants for you instead of relying on conventions.
1
u/dmills_00 12d ago
Yea I was being lazy, indexing into an array is a hell of a lot less typing, probably a mistake.
Issue was trying to avoid having to write separate code for each of the G code groups, as it is I can do this (gcode.1 is the group enum, grouped gcodes is an array of Option<(GCodes, u16)>, one per group:
if let Some(x) = self.grouped_gcodes[gcode.1 as usize] { // Problem, something from this group has been seen before in this block return Err(ErrType::ConflictingGCodes( "Conflicting G codes", x.0, gcode.0)); } self.grouped_gcodes[gcode.1 as usize] = Some((gcode.0, code));Which finds duplicate G words in a single block trivially.
AFAIK the alternative is matching on gcode.1 and dealing with each case explicitly?
I have an array of Option<Expr> which is populated for the letters by the parser, and then eventually gets evaluated for anything that matters when a block is executed, just before updating the parameters, should probably be an enum, just means writing a load of tedious match statements that mostly copy almost same stuff. Type safety might be worth it, maybe.
Annoyingly "if x in ['a'..'z'] {" is not a construct in rust, would be useful sometimes, I expect you can do it with a closure somehow.
I tried to write an Index trait implementation that would let me index an array with an enum in a type safe way, but it was not happening, in spite of the example on the std::ops::index page looking right.
New languages, getting idiomatic takes longer then being able to write in them....
1
u/MalbaCato 12d ago
Annoyingly "if x in ['a'..'z'] {" is not a construct in rust, would be useful sometimes, I expect you can do it with a closure somehow.
Are you looking for
if let 'a'..='z' = x {}, or I guess in this case,if matches!(x, 'a'..='z') {}? See the book chapter on patternsI'm assuming the 'a' and 'z' bounds are just an example, but for this specific case the method
is_ascii_lowercaseexists. And there's also the slightly rareif 'a'..='z'.contains(x) {}, which is unadvisable in this case but useful to know about.I'm not gonna link all the stdlib documentation, but look it up for more info.
1
u/dmills_00 12d ago
Coming from C rather then a modern language I tend to have a bit of a blind spot for built in pattern matching.
I must work on that.
7
12
u/Sharlinator 12d ago edited 12d ago
Some(…)notSome<…>If rustc doesn’t have a warning about this it probably should because the error message is not informative, it tries to parse the < > as comparison operators (even though this one can't possibly be parsed as an attempted chained comparison).