Enum ve Pattern Matching: Rust'ta Güçlü Veri Yapıları

2023-08-25

Rust programlama dilinde enum ve pattern matching özellikleri, tip güvenliği ve kod okunabilirliği için oldukça önemli ve güçlüdür. enum (enumerasyonlar), farklı varyantları (variant) olan bir türü temsil eder. pattern matching ise, bu varyantları kolayca ve güvenli bir şekilde ele almanıza olanak tanır.

Enum Nedir?

enum keyword’ü ile bir enumerasyon oluşturabilirsiniz. Her bir “varyant” farklı bir olası değeri temsil eder.

enum Renk {
    Kirmizi,
    Yesil,
    Mavi,
}

Bu örnekte Renk adlı bir enum tanımladık ve içerisine Kirmizi, Yesil, ve Mavi adlı varyantları ekledik.

Enum’ların Kullanımı

Enum varyantlarını oluşturmak için :: operatörünü kullanırız.

let r = Renk::Kirmizi;

Pattern Matching ile Enum

match ifadesi, bir enum‘ın hangi varyant olduğunu kontrol etmek için kullanılır.

fn ana_renk_yazdir(renk: Renk) {
    match renk {
        Renk::Kirmizi => println!("Bu renk kırmızıdır."),
        Renk::Yesil => println!("Bu renk yeşildir."),
        Renk::Mavi => println!("Bu renk mavidir."),
    }
}

Enum’lara Veri Eklemek

Enum varyantları da veri tutabilir.

enum Mesaj {
    Yaz(String),
    Oku(u64),
    Sil,
}

Pattern Matching ile Verili Enum

fn mesaj_isle(mesaj: Mesaj) {
    match mesaj {
        Mesaj::Yaz(icerik) => println!("Yazılacak mesaj: {}", icerik),
        Mesaj::Oku(id) => println!("Okunacak mesajın ID'si: {}", id),
        Mesaj::Sil => println!("Mesaj silinecek"),
    }
}

if let ile Daha Basit Pattern Matching

Sadece bir varyant ile ilgileniyorsanız, if let kullanabilirsiniz.

if let Mesaj::Yaz(icerik) = mesaj {
    println!("Yazılacak mesaj: {}", icerik);
}

Option ve Result Enumları

Rust’ta çok sık kullanılan iki özel enum vardır: Option ve Result.

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

enum Result<T, E> {
    Ok(T),
    Err(E),
}

Örneğin, bir değer olabilir ya da olmayabilirse Option kullanılır.

let x: Option<i32> = Some(5);
let y: Option<i32> = None;

Enum ve Methodlar

Enum’lar da impl bloğu ile method tanımlayabilir.

impl Mesaj {
    fn yaz_yeni(icerik: String) -> Mesaj {
        Mesaj::Yaz(icerik)
    }
}

Kısacası, Rust’ta enum ve pattern matching ile kod daha okunabilir, daha güvenli ve daha esnek hale gelir.



More posts like this

Rusts Drop Trait: Mastering Resource Management with Precision

2024-05-01 | #rust

Efficient resource management is pivotal in systems programming, where the reliability and performance of applications heavily depend on the meticulous management of resources. Rust’s Drop trait provides a sophisticated mechanism for deterministic resource handling, markedly enhancing the predictability and efficiency of resource management over traditional methods like garbage collection (GC) and manual resource management. The Challenge of Resource Management Resources such as memory, files, network connections, and locks are finite and critical for the stability of applications.

Continue reading 


Function Pointers in Rust: A Comprehensive Guide

2024-04-28 | #rust

Function pointers are a powerful feature in Rust, enabling developers to dynamically manage and manipulate references to functions, fostering customizable behaviors and efficient complex design patterns. This guide dives into their practical applications, syntax, advanced use cases, and best practices, and it compares them with closures and trait objects. Type Safety and Performance: A Balancing Act Rust is a language that does not compromise on safety or performance, and function pointers are no exception:

Continue reading 


Lifetime Specifiers for Tuple Structs and Enums

2024-04-17 | #rust

In Rust, lifetime specifiers are crucial for managing references and ensuring that data referenced by a pointer isn’t deallocated as long as it’s needed. Lifetime specifiers aid Rust’s borrow checker in ensuring memory safety by explicitly defining how long references within structs, enums, or functions are valid. This is especially important when dealing with non-‘static lifetimes, or data that might not live for the entire duration of the program. Below, I’ll explain how you can apply lifetime specifiers to tuple-structs and enums and then use metaphors to make the concept more engaging and intuitive.

Continue reading 