Rust for JavaScript Developers - Pattern Matching and Enums

栏目: IT技术 · 发布时间: 4年前

内容简介:This is the fourth part in a series about introducing the Rust language to JavaScript developers. Here are the past chapters:To understand Pattern Matching, let’s start with something familiar in JavaScript - Switch Case.Here’s a simple example that uses

This is the fourth part in a series about introducing the Rust language to JavaScript developers. Here are the past chapters:

  1. Tooling Ecosystem Overview
  2. Variables and Data Types
  3. Functions and Control Flow

Pattern Matching

To understand Pattern Matching, let’s start with something familiar in JavaScript - Switch Case.

Here’s a simple example that uses switch case in JavaScript:

function print_color(color) {
  switch (color) {
    case "rose":
      console.log("roses are red,");
      break;
    case "violet":
      console.log("violets are blue,");
      break;
    default:
      console.log("sugar is sweet, and so are you.");
  }
}

print_color("rose"); // roses are red,
print_color("violet"); // violets are blue,
print_color("you"); // sugar is sweet, and so are you.

Here’s the equivalent Rust code:

fn print_color(color: &str) {
  match color {
    "rose" => println!("roses are red,"),
    "violet" => println!("violets are blue,"),
    _ => println!("sugar is sweet, and so are you."),
  }
}

fn main() {
  print_color("rose"); // roses are red,
  print_color("violet"); // violets are blue,
  print_color("you"); // sugar is sweet, and so are you.
}

Most of the code should be immediately understandable. The match expression has the following signature:

match VALUE {
  PATTERN1 => EXPRESSION1,
  PATTERN2 => EXPRESSION2,
  PATTERN3 => EXPRESSION3,
}

The fat arrow => syntax might trip us up because of the similarities with JavaScript arrow functions but they’re unrelated. The last pattern that uses underscore _ is called the catchall pattern and is similar to the default case in switch case. Each PATTERN => EXPRESSION combination is called a match arm .

The above example doesn’t really convey how useful pattern matching is - it just looks like switch case with a different syntax and a fancy name. Let’s talk about destructuring and enums to understand why pattern matching is useful.

Destructuring

Destructuring is the process of extracting the inner fields of an array or struct into separate variables. If you have used destructuring in JavaScript, it is very similar in Rust.

Here’s an example in JavaScript:

let rgb = [96, 172, 57];
let [red, green, blue] = rgb;
console.log(red); // 96
console.log(green); // 172
console.log(blue); // 57

let person = { name: "shesh", city: "singapore" };
let { name, city } = person;
console.log(name); // name
console.log(city); // city

Here’s the same example in Rust:

struct Person {
  name: String,
  city: String,
}

fn main() {
  let rgb = [96, 172, 57];
  let [red, green, blue] = rgb;
  println!("{}", red); // 96
  println!("{}", green); // 172
  println!("{}", blue); // 57

  let person = Person {
    name: "shesh".to_string(),
    city: "singapore".to_string(),
  };
  let Person { name, city } = person;
  println!("{}", name); // name
  println!("{}", city); // city
}

Comparing Structs

It’s very common to write “if this then that” type of code. Combining destructuring and pattern matching allows us to write these type of logic in a very concise way.

Let’s take this following example in JavaScript. It’s contrived but you have probably written something like this sometime in your career:

const point = { x: 0, y: 30 };
const { x, y } = point;

if (x === 0 && y === 0) {
  console.log("both are zero");
} else if (x === 0) {
  console.log(`x is zero and y is ${y}`);
} else if (y === 0) {
  console.log(`x is ${x} and y is zero`);
} else {
  console.log(`x is ${x} and y is ${y}`);
}

Let’s write the same code in Rust using pattern matching:

struct Point {
  x: i32,
  y: i32,
}

fn main() {
  let point = Point { x: 10, y: 0 };

  match point {
    Point { x: 0, y: 0 } => println!("both are zero"),
    Point { x: 0, y } => println!("x is zero and y is {}", y),
    Point { x, y: 0 } => println!("x is {} and y is zero", x),
    Point { x, y } => println!("x is {} and y is {}", x, y),
  }
}

It’s a bit concise compared to the if else logic but also might be confusing as we’re performing comparison, destructuring and variable binding at the same time.

This is how it looks like visually:

Rust for JavaScript Developers - Pattern Matching and Enums Rust for JavaScript Developers - Pattern Matching and Enums

We begin to see why it’s named as “pattern matching” - we take an input and see which pattern in the match arms “fits” better - It’s like the shape sorter toys that kids play with. Apart from comparison, we also do variable binding in the 2nd, 3rd and 4th match arms. We pass variables x or y or both to their respective expressions.

Pattern matching is also exhaustive - that is, it forces you to handle all the possible cases. Try removing the last match arm and Rust won’t let you compile the code.

Enum

JavaScript doesn’t have Enums but if you’ve used TypeScript, you can think of Rust’s Enums as a combination of TypeScript’s Enums and TypeScript’s Discriminated Unions

In the simplest case, Enums can be used as a group of constants.

For example, even though JavaScript doesn’t have Enums, you might have used this pattern:

const DIRECTION = {
  FORWARD: "FORWARD",
  BACKWARD: "BACKWARD",
  LEFT: "LEFT",
  RIGHT: "RIGHT",
};

function move_drone(direction) {
  switch (direction) {
    case DIRECTION.FORWARD:
      console.log("Move Forward");
      break;
    case DIRECTION.BACKWARD:
      console.log("Move Backward");
      break;
    case DIRECTION.LEFT:
      console.log("Move Left");
      break;
    case DIRECTION.RIGHT:
      console.log("Move Right");
      break;
  }
}

move_drone(DIRECTION.FORWARD); // "Move Forward"

Here, we could’ve defined the FORWARD, BACKWARD, LEFT and RIGHT as separate constants, yet grouping it inside the DIRECTION object has the following benefits:

  • The names FORWARD, BACKWARD, LEFT and RIGHT are namespaced under DIRECTION so naming conflicts can be avoided
  • It is self-documenting as we can quickly see all the valid directions available in the codebase

However, there are some problems with this approach:

  • What if someone passes NORTH or UP as an argument to move_drone? To fix this, we can add a validation to make sure that only values present in the DIRECTION object is allowed in the move function.
  • What if we decide to support UP and DOWN in future or rename LEFT/RIGHT to PORT/STARBOARD? We need to find all the places where similar switch-case or if-else is used. There’s a chance that we might miss out a few places which would cause issues in production.

Enums in strongly typed languages like Rust are more powerful as they solve these problems without us writing extra code.

  • If a function can take in only a small set of valid inputs, Enums can be used to enforce this constraint
  • Enums with pattern matching force you to cover all cases. Useful when you’re updating Enums in future

Here’s the equivalent Rust example:

enum Direction {
  Forward,
  Backward,
  Left,
  Right,
}

fn move_drone(direction: Direction) {
  match direction {
    Direction::Forward => println!("Move Forward"),
    Direction::Backward => println!("Move Backward"),
    Direction::Left => println!("Move Left"),
    Direction::Right => println!("Move Right"),
  }
}

fn main() {
  move_drone(Direction::Forward);
}

We access the variants inside Enum using the :: notation. Try editing this code by calling “move_drone(Direction::Up)” or adding “Down” as a new item in the Direction enum. In the first case, the compiler will throw an error saying that “Up” is not found in “Direction” and in the second case, the compiler will complain that we haven’t covered “Down” in the match block.

Rust Enums can do much more than act as a group of constants - we can also associate data with an Enum variant.

enum Direction {
  Forward,
  Backward,
  Left,
  Right,
}

enum Operation {
  PowerOn,
  PowerOff,
  Move(Direction),
  Rotate,
  TakePhoto { is_landscape: bool, zoom_level: i32 },
}

fn operate_drone(operation: Operation) {
  match operation {
    Operation::PowerOn => println!("Power On"),
    Operation::PowerOff => println!("Power Off"),
    Operation::Move(direction) => move_drone(direction),
    Operation::Rotate => println!("Rotate"),
    Operation::TakePhoto {
      is_landscape,
      zoom_level,
    } => println!("TakePhoto {}, {}", is_landscape, zoom_level),
  }
}

fn move_drone(direction: Direction) {
  match direction {
    Direction::Forward => println!("Move Forward"),
    Direction::Backward => println!("Move Backward"),
    Direction::Left => println!("Move Left"),
    Direction::Right => println!("Move Right"),
  }
}

fn main() {
  operate_drone(Operation::Move(Direction::Forward));
  operate_drone(Operation::TakePhoto {
    is_landscape: true,
    zoom_level: 10,
  })
}

Here, we’ve added one more Enum called Operation that contains “unit like” variants (PowerOn, PowerOff, Rotate) and “struct like” variants (Move, TakePhoto). Notice how we’ve used pattern matching with destructuring and variable binding.

If you’ve used TypeScript or Flow, this is similar to discriminated unions or sum types :

interface PowerOn {
  kind: "PowerOn";
}

interface PowerOff {
  kind: "PowerOff";
}

type Direction = "Forward" | "Backward" | "Left" | "Right";

interface Move {
  kind: "Move";
  direction: Direction;
}

interface Rotate {
  kind: "Rotate";
}

interface TakePhoto {
  kind: "TakePhoto";
  is_landscape: boolean;
  zoom_level: number;
}

type Operation = PowerOn | PowerOff | Move | Rotate | TakePhoto;

function operate_drone(operation: Operation) {
  switch (operation.kind) {
    case "PowerOn":
      console.log("Power On");
      break;
    case "PowerOff":
      console.log("Power Off");
      break;
    case "Move":
      move_drone(operation.direction);
      break;
    case "Rotate":
      console.log("Rotate");
      break;
    case "TakePhoto":
      console.log(`TakePhoto ${operation.is_landscape}, ${operation.zoom_level}`);
      break;
  }
}

function move_drone(direction: Direction) {
  switch (direction) {
    case "Forward":
      console.log("Move Forward");
      break;
    case "Backward":
      console.log("Move Backward");
      break;
    case "Left":
      console.log("Move Left");
      break;
    case "Right":
      console.log("Move Right");
      break;
  }
}

operate_drone({
  kind: "Move",
  direction: "Forward",
});

operate_drone({
  kind: "TakePhoto",
  is_landscape: true,
  zoom_level: 10,
});

Option

We learnt about the Option type inchapter 2. Option is actually an Enum with two variants - Some and None :

enum Option<T> {
  Some(T),
  None,
}

This is how we handled the Option value in that chapter:

fn read_file(path: &str) -> Option<&str> {
  let contents = "hello";

  if path != "" {
    return Some(contents);
  }

  return None;
}

fn main() {
  let file = read_file("path/to/file");

  if file.is_some() {
    let contents = file.unwrap();
    println!("{}", contents);
  } else {
    println!("Empty!");
  }
}

Using pattern matching, we can refactor the logic as follows:

fn main() {
  let file = read_file("path/to/file");

  match file {
    Some(contents) => println!("{}", contents),
    None => println!("Empty!"),
  }
}

Thanks for reading! Feel free to follow me in Twitter for updates :)


以上所述就是小编给大家介绍的《Rust for JavaScript Developers - Pattern Matching and Enums》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

JAVA核心技术卷2

JAVA核心技术卷2

Cay S. Horstmann、Gary Cornell / 陈昊鹏、王浩、姚建平 / 机械工业出版社 / 2008-12 / 118.00元

《JAVA核心技术卷2:高级特征》是Java技术权威指南,全面覆盖Java技术的高级主题,包括流与文件、XML、网络、数据库编程、高级Swing、高级 AWT、JavaBean构件、安全、分布式对象、脚本、编译与注解处理等,同时涉及本地化、国际化以及Java SE 6的内容。《JAVA核心技术卷Ⅱ:高级特征》对Java技术的阐述精确到位,叙述方式深入浅出,并包含大量示例,从而帮助读者充分理解Jav......一起来看看 《JAVA核心技术卷2》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

SHA 加密
SHA 加密

SHA 加密工具

html转js在线工具
html转js在线工具

html转js在线工具