Blog post: Mixing matching, mutation, and moves in Rust


#1

(This already got linked on reddit and hackernews, but I figured I would also mention it here, since not everyone is on those forums.)

I wrote a blog post discussing match: Mixing matching, mutation, and moves in Rust

The post has a quick introduction to what pattern matching is (since some people haven’t seen things more powerful than a switch statement before), and then delves into some of the fun things Rust does to combine imperative programming with such a construct.

Happy to get feedback!


#2

Many other languages offer a pattern matching construct (ML and
various macro-based match implementations in Scheme both come to
mind), but not all of them have this restriction.

Ada has a simplified pattern matching and full exhaustion checking. It might not be as obvious as in Rust, since the discriminant is checked and then one simply accesses the fields. But the field-accesses are checked, it’s not a tagged union where you can access all fields as you wish, no matter what the discriminant is. Here’s an example (taken and simplified from http://www.isa.uniovi.es/docencia/TiempoReal/Recursos/textbook/aps12-4.htm)

SUBTYPE NameRange IS Positive RANGE 1..20;
SUBTYPE NameType IS String(NameRange);
SUBTYPE WorkHours IS Float RANGE 0.0..168.0;
SUBTYPE Wage IS Float RANGE 0.0..999999;
TYPE PayCategories IS (Unknown, Professional, Clerical);

TYPE Employee ( PayStatus : PayCategories := Unknown) IS RECORD
  Name      : NameType;
    
  CASE PayStatus IS
    WHEN Professional =>
      MonthSalary : Wage;
    WHEN Clerical =>
      HourlyWage  : Wage;
      HoursWorked : WorkHours;
    WHEN Unknown =>
      NULL;
  END CASE;
END RECORD; 

-- printing the record
Ada.Text_IO.Put(Item => "Employee Name ");
Ada.Text_IO.Put(Item => CurrentEmp.Name(1..CurrentEmp.NameLength));
Ada.Text_IO.New_Line;

CASE CurrentEmp.PayStatus IS

  WHEN Unknown =>
    Ada.Text_IO.Put(Item => "Unknown pay status!");
    Ada.Text_IO.New_Line;

  WHEN Professional =>
    Ada.Text_IO.Put("Monthly Salary is $");
    Ada.Float_Text_IO.Put
      (Item=>CurrentEmp.MonthSalary, Fore=>1, Aft=>2,Exp=>0);
    Ada.Text_IO.New_Line;

  WHEN Clerical =>
    Ada.Text_IO.Put("Hourly wage is $");
    Ada.Float_Text_IO.Put(Item=>CurrentEmp.HourlyWage, Fore=>1, Aft=>2, Exp=>0);
    Ada.Text_IO.New_Line;
    Ada.Text_IO.Put("Hours worked this week ");
    Ada.Float_Text_IO.Put(Item=>CurrentEmp.HoursWorked, Fore=>1, Aft=>2,Exp=>0);
    Ada.Text_IO.New_Line

END CASE;