Menu
Coddy logo textTech

הרצת המסך

חלק מהיחידה תכנות מונחה עצמים במסלול ה-Rust של Coddy. שיעור 53 מתוך 61.

challenge icon

אתגר

קל

ברכות על שהגעת לשלב האחרון בפרויקט Document System! בנית את כל החלקים בנפרד: את המאפיין Draw, את TextField, את Button ואת Screen. עכשיו הגיע הזמן להוסיף ל-Screen שלך את היכולת להציג את כל הרכיבים שלו בבת אחת, באמצעות קריאה יחידה למתודה.

תשלים את הפרויקט שלך על ידי הוספת מתודת run למבנה Screen. המתודה הזו תעבור על כל הרכיבים המאוחסנים במסך ותקרא ל-draw() בכל אחד מהם, וכך תהפוך את מערכת המסמכים כולה לפעילה.

קובצי הפרויקט שלך:

  • draw.rs: מאפיין ה-Draw שלך עם המתודה draw.
  • text_field.rs: הרכיב TextField שלך, שמדפיס Text: {content}.
  • button.rs: הרכיב Button שלך, שמדפיס Button: {label} (width: {width}).
  • screen.rs: המבנה Screen שלך עם המתודות new ו-add. הוסף מתודת run שמקבלת &self וקוראת ל-draw() בכל רכיב באוסף.
  • main.rs: חבר את הכול יחד: צור Screen, הוסף את הרכיבים שלך וקרא ל-run() כדי להציג את המסך כולו בפעולה אחת.

מתודת run מרכזת את לוגיקת ההצגה בתוך Screen, וכך פונקציית main שלך נשארת נקייה ופשוטה. במקום לעבור ידנית על הרכיבים בתוך main, פשוט קוראים ל-screen.run().

הקלט הבא יסופק:

  • השורה הראשונה: התוכן של שדה הטקסט
  • השורה השנייה: התווית של הכפתור
  • השורה השלישית: רוחב הכפתור (כמספר)

הפלט שלך צריך להציג כל רכיב בשורה נפרדת, לפי סדר הוספתם:

Text: Dashboard
Button: Save (width: 120)

נסו בעצמכם

mod draw;
mod text_field;
mod button;
mod screen;

use draw::Draw;
use text_field::TextField;
use button::Button;
use screen::Screen;

pub struct Label {
    pub text: String,
}

impl Draw for Label {
    fn draw(&self) {
        println!("{}", self.text);
    }
}

fn main() {
    let mut input1 = String::new();
    std::io::stdin().read_line(&mut input1).expect("Failed to read line");
    let content = input1.trim().to_string();

    let mut input2 = String::new();
    std::io::stdin().read_line(&mut input2).expect("Failed to read line");
    let label = input2.trim().to_string();

    let mut input3 = String::new();
    std::io::stdin().read_line(&mut input3).expect("Failed to read line");
    let width: u32 = input3.trim().parse().expect("Failed to parse width");

    let mut screen = Screen::new();

    let text_field = TextField { content };
    screen.add(Box::new(text_field));

    let button = Button { label, width };
    screen.add(Box::new(button));

    // TODO: החליפו את האיטרציה הידנית שלהלן בקריאה אחת ל-screen.run()
    for component in &screen.components {
        component.draw();
    }
}

כל השיעורים ביחידה תכנות מונחה עצמים

תרגלו בעצמכם: קומפיילר Rust אונליין