RSS Amplifier

Noratrieb's blog · Mar 17, 2023

Item Patterns And Struct Else

0
Sign in to vote or save

This page cannot be shown here. You can still read it on the original site — the toolbar below keeps your place in the directory.

Pattern matching One of my favourite features of Rust is pattern matching. It&rsquo;s a simple and elegant way to deal with not just structs, but also enums! enum ItemKind { Struct(String, Vec < Field > ), Function(String, Body), } impl ItemKind { fn name ( & self) -> & str { match self { Self::Struct(name, _) => name, Self::Function(name, _) => name, } } } Here, we have an enum and a function to…

Pattern matching

One of my favourite features of Rust is pattern matching. It’s a simple and elegant way to deal with not just structs, but also enums!

enum ItemKind {
 Struct(String, Vec<Field>),
 Function(String, Body),
}

impl ItemKind {
 fn name(&self) -> &str {
 match self {
 Self::Struct(name, _) => name,
 Self::Function(name, _) => name,
 }
 }
}

Here, we have an enum and a function to get the name out of this. In C, this would be very unsafe, as we cannot be guaranteed that our union has the right tag. But in Rust, the compiler nicely checks it all for us. It’s safe and expressive (just like many other features of Rust).

Read on /blog/posts/item-patterns-and-struct-else/

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.