AzLearn

تمرين إعادة البناء

Contact Search

أعد كتابة باحث جهات اتصال صغير يرشح النتائج من بيانات ثابتة أو ملف CSV.

rust ~14 دقيقة مبتدئ
أعد بناء الكود Rebuild

هذا هو الكود. اكتبه بنفسك.

الكود المرجعي
use std::env;
use std::fs;
use std::io;

#[derive(Debug)]
struct Contact {
    name: String,
    phone: String,
    city: String,
}

fn main() -> io::Result<()> {
    let query = env::args().nth(1).unwrap_or_default().to_lowercase();
    let contacts = load_contacts(env::args().nth(2))?;

    for contact in contacts {
        let searchable = format!("{} {} {}", contact.name, contact.phone, contact.city).to_lowercase();
        if query.is_empty() || searchable.contains(&query) {
            println!("{} | {} | {}", contact.name, contact.phone, contact.city);
        }
    }

    Ok(())
}

fn load_contacts(path: Option<String>) -> io::Result<Vec<Contact>> {
    let data = match path {
        Some(path) => fs::read_to_string(path)?,
        None => "name,phone,city\nAisha,0551112222,Riyadh\nOmar,0503334444,Jeddah\nSara,0545556666,Dammam\n".to_string(),
    };

    let contacts = data
        .lines()
        .skip(1)
        .filter_map(parse_contact)
        .collect();

    Ok(contacts)
}

fn parse_contact(line: &str) -> Option<Contact> {
    let fields: Vec<_> = line.split(',').map(str::trim).collect();

    Some(Contact {
        name: fields.get(0)?.to_string(),
        phone: fields.get(1)?.to_string(),
        city: fields.get(2)?.to_string(),
    })
}
اكتب هنا