Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match struct fields in Rust?

Tags:

Can Rust match struct fields? For example, this code:

struct Point {     x: bool,     y: bool, }  let point = Point { x: false, y: true };  match point {     point.x => println!("x is true"),     point.y => println!("y is true"), } 

Should result in:

y is true 
like image 890
maku Avatar asked Dec 30 '16 04:12

maku


People also ask

How do you access the fields and their values for a given struct in Rust?

To get a specific value from a struct, we use dot notation. For example, to access this user's email address, we use user1. email . If the instance is mutable, we can change a value by using the dot notation and assigning into a particular field.

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.

How do you match types in Rust?

Instead of matching on an element, call the method in the trait on it. TLDR: in Rust, to match over type, we create a trait, implement a function for each type and call it on the element to match. Surround it with backticks to mark it as code. Single backticks for inline code, triple backticks for code blocks.

How does match work in Rust?

Rust has an extremely powerful control flow construct called match that allows you to compare a value against a series of patterns and then execute code based on which pattern matches.


1 Answers

Can Rust match struct fields?

It is described in the Rust book in the "Destructuring structs" chapter.

match point {     Point { x: true, .. } => println!("x is true"),     Point { y: true, .. } => println!("y is true"),     _ => println!("something else"), } 
like image 189
aSpex Avatar answered Oct 06 '22 04:10

aSpex