Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore a member of a struct-like enum variant in pattern matching?

Tags:

enums

rust

How do I remove the unused_variables warning from the following code?

pub enum Foo {
    Bar {
        a: i32,
        b: i32,
        c: i32,
    },
    Baz,
}

fn main() {
    let myfoo = Foo::Bar { a: 1, b: 2, c: 3 };
    let x: i32 = match myfoo {
        Foo::Bar { a, b, c } => b * b,
        Foo::Baz => -1,
    };
    assert_eq!(x, 4);
}

I know I can ignore struct members after a certain point with:

Foo::Bar { a, .. } => // do stuff with 'a'

But I can't find documentation anywhere that explains how to ignore individual struct members.

Code on Rust Playground

like image 304
ampron Avatar asked Jun 25 '16 17:06

ampron


People also ask

How do you match enums in Rust?

Adding data to enum variantsCreated a new instance of the enum and assigned it to a variable. Put that variable in a match statement. Destructured the contents of each enum variant into a variable within the match statement.

Does Rust have pattern matching?

Patterns are a special syntax in Rust for matching against the structure of types, both complex and simple. Using patterns in conjunction with match expressions and other constructs gives you more control over a program's control flow.

What are structs and enums in Rust?

structs can be used to model cars and define state. methods and associated functions can be used to specify their behaviour. enums can be used to specify range of allowed values for a custom data type. traits can be used to describe shared behaviours across user-defined data types.

What is an enum in Rust?

An enum in Rust is a type that represents data that is one of several possible variants. Each variant in the enum can optionally have data associated with it: #![allow(unused_variables)] fn main() { enum Message { Quit, ChangeColor(i32, i32, i32), Move { x: i32, y: i32 }, Write(String), }


1 Answers

I know I can ignore struct members after a certain point with:

The .. is not positional. It just means "all the other fields":

Foo::Bar { b, .. } => b * b,
like image 185
Shepmaster Avatar answered Oct 06 '22 01:10

Shepmaster