r/learnrust • • 6d 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.

1 Upvotes

16 comments sorted by

12

u/Sharlinator 6d ago edited 6d ago

Some(…) not Some<…>

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

4

u/dmills_00 6d ago

Oh, thanks.

3

u/Demiu 6d ago

Bad warnings are a bug, needs a gh issue. Edit just saw ur other comment, nice

4

u/This_Growth2898 6d ago
- ...<...>
+ ...(...)

3

u/dmills_00 6d ago

Yea, got it.

Gets to a point where you cannot see the obvious after staring at it for 20 minutes.

2

u/projct 6d ago

Some(CutterComp::CompOff) and self.radius_compensation = Some(CutterComp::LeftFromTool(self.axis.get(&"d").cloned()));

2

u/dmills_00 6d ago

Oh FFS, thanks.

5

u/projct 6d 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

u/dmills_00 6d ago

Looks like you got there ahead of me.

1

u/projct 6d ago

that was not me! guess everyone wants to be helpful.

2

u/projct 6d ago

also, a tip or two.

  1. 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 owned Option<Expr>. no string lookups, no misspelled keys.

  1. 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-map crate.

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 6d 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 6d 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 patterns

I'm assuming the 'a' and 'z' bounds are just an example, but for this specific case the method is_ascii_lowercase exists. And there's also the slightly rare if '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 6d 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

u/Sharlinator 6d ago

Opened #166133 because the error message is super unhelpful.