Rust bit by bit: how to write the expression in pattern matching

Time:2021-8-23

Pattern matching is often used in rust. Match expression is the most commonly used expression for pattern matching

The match expression is roughly divided into three parts: match keyword, head expression and match block. This article mainly discusses how to write head expression

Head expression

As we know, there are only two expressions in rust:Position expression, Value expressionSimilarly, the rust expression context also includesPosition expression context, Value expression contextThe position of. Head expression belongs to the context of position expression, which can be position expression or value expression, and its behavior is different

If it is a value expression, it will evaluate the expression, put the result in a temporary position, and then compare whether there are qualified branches according to the order of match branches. The first matched branch is the target branch of pattern matching, and the temporary variable just created can be used in the branch

match 5+3 {
    8 => println!("equals!"),
    _ => println!("not equals!"),
}

If the head expression is a location expression, a temporary variable will not be allocated, but a binding will be created. Whether to copy or move semantics depends on whether the type implements copy

let x = 1;

match x {
    1 => println!("one"),
    _ => println!("something else"),
}

X here is a position expression, so the whole code is equivalent to the following:

let x = 1;
let b = x; //  Here, because x is I32, it implements copy, so it is copy semantics
match b {
    1 => println!("one"),
    _ => println!("something else"),
}

In case of moving semantics, the ownership of the variable will be transferred to the match expression. When the match expression ends, the variable will be destroyed

If you do not want to transfer ownership, you can use ref or ref mut to declare a reference binding and match by reference:

let x = 1;

match ref x {
    &1 => println!("one"),
    _ => println!("something else"),
}

This code is equivalent to:

let x = 1;
let b = &x;
match b {
    &1 => println!("one"),
    _ => println!("something else"),
}

Here are some points that are difficult for me to understand: when the matched dereference expression in the head expression is actually equivalent to the matched reference

let y = match *x { 0 => "zero", _ => "some" };
let z = match x { &0 => "zero", _ => "some" };

assert_eq!(y, z);

reference material

Recommended Today

Apply function family

#apply(X,MARGIN,FUN,…) #Sum by row apply(df,1,sum) #Sum by column apply(df,2,sum) #Reassign all elements in DF apply(df,c(1,2),function(x){x<-100}) #Calculate the mean, variance and maximum value of each column in DF (see the figure below for apply method and for method) apply(df,2,function(x){c(mean(x),var(x),max(x))}) #Write a user-defined function and apply to find the mean, variance and maximum of each column in […]