Why do I get an error when pattern matching a struct-like enum variant with fields? - enums

I can't get rid of an error on this code:
#[derive(PartialEq, Copy, Clone)]
pub enum OperationMode {
ECB,
CBC { iv: [u8; 16] },
}
pub struct AES {
key: Vec<u8>,
nr: u8,
mode: OperationMode,
}
impl AES {
pub fn decrypt(&mut self, input: &Vec<u8>) {
match self.mode {
OperationMode::ECB => {},
OperationMode::CBC(_) => {},
};
}
}
The pattern matching at the end of the decrypt function gives an error:
error[E0532]: expected tuple struct/variant, found struct variant `OperationMode::CBC`
--> src/main.rs:17:13
|
17 | OperationMode::CBC(_) => {},
| ^^^^^^^^^^^^^^^^^^ did you mean `OperationMode::CBC { /* fields */ }`?
It tells me to look at the output of rustc --explain E0532 for help, which I did.
They show this example of wrong code:
enum State {
Succeeded,
Failed(String),
}
fn print_on_failure(state: &State) {
match *state {
// error: expected unit struct/variant or constant, found tuple
// variant `State::Failed`
State::Failed => println!("Failed"),
_ => ()
}
}
In this example, the error occurs because State::Failed has a field which isn't matched. It should be State::Failed(ref msg).
In my case I'm matching the field of my enum because I'm doing OperationMode::CBC(_). Why does the error happen?

Enum variants have three possible syntaxes:
unit
enum A { One }
tuple
enum B { Two(u8, bool) }
struct
enum C { Three { a: f64, b: String } }
You have to use the same syntax when pattern matching as the syntax the variant was defined as:
unit
match something {
A::One => { /* Do something */ }
}
tuple
match something {
B::Two(x, y) => { /* Do something */ }
}
struct
match something {
C::Three { a: another_name, b } => { /* Do something */ }
}
Beyond that, you can use various patterns that allow ignoring a value, such as _ or ... In this case, you need curly braces and the .. catch-all:
OperationMode::CBC { .. } => { /* Do something */ }
See also:
Ignoring Values in a Pattern in The Rust Programming Language
Appendix B: Operators and Symbols in The Rust Programming Language
How to match struct fields in Rust?

Related

Prae:Wrapper: need to use iter_mut of interior Vec but Prae:Wrapper only provides immutable access

I'm using the prae crate for validation and the following function gives me errors:
fn advance_rotors(&mut self) {
self.rotors.get()[0].rotate();
let mut iterhandle = self.rotors.iter_mut().peekable(); // Error at iter_mut() #0599
while let Some(el) = iterhandle.next() {
match iterhandle.peek_mut() {
Some(next_rotor) => match el.should_advance_next() {
true => {
next_rotor.rotate(); // This line requires mutable access to next_rotor
}
false => (),
},
None => (),
}
}
}
and the definition of my struct here:
pub struct Enigma {
reflector: Reflector,
rotors: RotorConfig, // Only mutable via getter and setter functions
}
the struct of interest here is RotorConfig which is generated using the define! macro from prae. Here's the code:
prae::define! {
#[derive(Debug)]
RotorConfig: Vec<Rotor>; // I need to be able to call the rotate method of each rotor in this vec. This requires mutability
validate(RotorConfigError) |config| {
match config.len(){
3..=4 => (),
_ => return Err(RotorConfigError::Size)
}
match config.iter().unique().count(){
3..=4 =>(),
_ => return Err(RotorConfigError::Duplicate)
}
Ok(())
};
}
the issue stems from the fact that prae only allows for immutable access to the internal representation via getter and setter functions so as to ensure the validity of the values inside. As you can see in my advance_rotors function I wrote before implementing validation I'm getting an error because I need to call rotor.rotate mutably. I'm at a loss as to how to accomplish this
After posting this I realized that I can simply provide interior mutability by using the following impl block
impl RotorConfig{
fn advance_rotors(&mut self)
{
self.0[0].rotate();
let mut iterhandle = self.0.iter_mut().peekable();
while let Some(el) = iterhandle.next() {
match iterhandle.peek_mut() {
Some(next_rotor) => match el.should_advance_next() {
true => {
next_rotor.rotate();
}
false => (),
},
None => (),
}
}
}
}
As you can see the function largely remains unchanged except that we replace self.rotors with self.0

How to read a value of an enum which associates with a custom type in Rust?

I have an implementation in Rust as follows. In the main function, I am reading a value in SalaryRange enum and this will display High("So High").
// This can be a complex type, just using string for the question
type SRange = String;
type SalEnu = SalaryRange<SRange>;
struct User<SRange> {
username: String,
email: String,
sign_in_count: u64,
active: bool,
income: Income<SRange>,
}
struct Income<SRange> {
salary_range: SalaryRange<SRange>
}
#[derive(Debug)]
enum SalaryRange<SRange> {
Low(SRange),
Mid(SRange),
High(SRange),
}
fn main() {
let user1 = User {
email: String::from("test#email.com"),
username: String::from("test_name"),
active: true,
sign_in_count: 1,
income: Income {
salary_range: (
SalaryRange::High("So High")
)
},
};
let mut srange: SalaryRange<&str> = user1.income.salary_range;
println!("{:?}", srange);
}
Link for this example can be found here.
Just wanted to know if there is a possibility to read and print the value in that enum as println!("{:?}", srange::High);, just to print out the string value?
I only want to print the value So High.
If I use srange::High This will throw an error saying
println!("{:?}", srange::High);
| ^^^^^^ use of undeclared type or module `srange`
error: aborting due to previous error
You can implement a method on your enum to extract the value:
#[derive(Debug)]
enum SalaryRange<S> {
Low(S),
Mid(S),
High(S),
}
impl<S> SalaryRange<S> {
fn value(&self) -> &S {
match self {
SalaryRange::Low(value) => value,
SalaryRange::Mid(value) => value,
SalaryRange::High(value) => value,
}
}
}
println!("{:?}", srange.value());
You can pattern match srange with the if let syntax.
if let SalaryRange::High(s) = srange {
println!("{}", s);
}
will print "so high".
I know it's been a while since the question has been opened, but I would like to complete Peter's answer.
There is a more idiomatic way to achieve what you want. Just implement the std::fmt::Display trait to your enum as following:
pub enum SalaryRange {
LOW(String),
MID(String),
HIGH(String),
}
impl std::fmt::Display for SalaryRange {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let content = match self {
SalaryRange::LOW(content) => content,
SalaryRange::MID(content) => content,
SalaryRange::HIGH(content) => content,
};
write!(f, "{}", content)
}
}
The std::fmt::Display trait allows you to display the content held by your enum value like this:
let salary_range = SalaryRange::HIGH("So high".to_string());
println!("{}", salary_range);
// outputs: "So high"
This should work with any type.
Playground to test it: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=eaea33a955dc9dcd81a4b96ec22d82bd

What does { .. } mean in a pattern?

I found the following piece of code in the doc about actix:
#[macro_use]
extern crate failure;
use actix_web::{error, http, HttpResponse};
#[derive(Fail, Debug)]
enum UserError {
#[fail(display = "Validation error on field: {}", field)]
ValidationError { field: String },
}
impl error::ResponseError for UserError {
fn error_response(&self) -> HttpResponse {
match *self {
UserError::ValidationError { .. } =>
HttpResponse::new(http::StatusCode::BAD_REQUEST),
}
}
}
What does { .. } mean here?
It's a pattern-matching destructuring wildcard that allows one to not need to specify all the members of an object. In this case:
UserError::ValidationError { .. }
It is enough for that match branch that the enum variant is ValidationError, regardless of its contents (in this case field):
enum UserError {
#[fail(display = "Validation error on field: {}", field)]
ValidationError { field: String },
}
It is also useful when one is concerned only with some members of an object; consider a Foo struct containing baz and bar fields:
struct Foo {
bar: usize,
baz: usize,
}
If you were only interested in baz, you could write:
fn main() {
let x = Foo { bar: 0, baz: 1 };
match x {
Foo { baz, .. } => println!("{}", baz), // prints 1
_ => (),
}
}

How to compare enum without pattern matching

I want to apply filter on an iterator and I came up with this one and it works, but it's super verbose:
.filter(|ref my_struct| match my_struct.my_enum { Unknown => false, _ => true })
I would rather write something like this:
.filter(|ref my_struct| my_struct.my_enum != Unknown)
This gives me a compile error
binary operation `!=` cannot be applied to type `MyEnum`
Is there an alternative to the verbose pattern matching? I looked for a macro but couldn't find a suitable one.
Use matches!, e.g.:
matches!(my_struct.my_enum, Unknown)
Alternatively, you can use PartialEq trait, for example, by #[derive]:
#[derive(PartialEq)]
enum MyEnum { ... }
Then your "ideal" variant will work as is. However, this requires that MyEnum's contents also implement PartialEq, which is not always possible/wanted.
I'd use pattern matching, but I'd move it to a method on the enum so that the filter closure is tidier:
#[derive(Debug)]
enum Thing {
One(i32),
Two(String),
Unknown,
}
impl Thing {
fn is_unknown(&self) -> bool {
match *self {
Thing::Unknown => true,
_ => false,
}
}
}
fn main() {
let things = [Thing::One(42), Thing::Two("hello".into()), Thing::Unknown];
for t in things.iter().filter(|s| !s.is_unknown()) {
println!("{:?}", t);
}
}
You can combine this with the matches macro as well:
fn is_unknown(&self) -> bool {
matches!(self, Thing::Unknown)
}
See also:
Compare enums only by variant, not value
You can use if let Some(x) = option { then } idiom with the same if let construct but without destructuring:
if let Unknown = my_struct.my_enum { false } else { true }

Return an inline-defined enum from a function?

I'm diving into rust, and I'm trying to do something like this:
match send("select * from User;") {
ConnError => println!("Connection error!"),
DBError(e) => println!("Database error {}", e),
Ok(response) => {
...
}
}
and I'm trying to figure out a compact way of defining the send function. I saw the Result enum, but it only handles one kind of error at a time. I was hoping that I could define my own enum like this:
fn send(query: str) -> enum { Ok(Box<Response>), ConnError, DBError(str) } {
...
}
alas, it is not possible, it's complaining about the unexpected 'enum' keyword. Is there any way to do what I'm trying here, or perhaps make Result handle multiple error types? Thanks!
As you say, you can use Result but you have to define the enum with your error types separately, as you can't define it directly in the return of your function.
Something like this:
use std::rand::distributions::{IndependentSample, Range};
fn main() {
match send("select * from foo") {
Ok(Response) => println!("response"),
Err(e) => match e {
ConnError => println!("connection error"),
DbError(err) => println!("{}", err)
}
}
}
// the enum with your errors
enum DataLayerError {
ConnError,
DbError(String)
}
struct Response; /*...*/
fn send(_query: &str) -> Result<Response, DataLayerError> {
let between = Range::new(0u, 2);
let mut rng = std::rand::task_rng();
// return a random result
match between.ind_sample(&mut rng) {
0 => Ok(Response),
1 => Err(DbError("yikes".to_string())),
2 => Err(ConnError),
_ => unreachable!()
}
}

Resources