0Pricing
Learn Rust Coding · 강의

즉시 모드 UI 기초

egui가 렌더링하는 방식을 이해해 보세요.

즉시 모드 UI 기초은(는) CoddyKit의 무료 Learn Rust Coding 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Learn Rust Coding 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What Immediate Mode Means

egui is an immediate-mode GUI library. Unlike retained-mode toolkits (GTK, Qt) where you build a persistent widget tree, egui rebuilds the entire UI from scratch on every frame.

Your code runs top-to-bottom each frame, emitting widgets as function calls. There is no stored node graph — the UI is just a side effect of running your closure.

The Update Loop

An egui app implements eframe::App, whose update method is called once per frame, typically 60 times a second.

Inside update you describe what the UI should look like right now, given current state. egui diffs nothing — it simply re-emits everything.

impl eframe::App for MyApp {
    fn update(&mut self, ctx: &egui::Context, _f: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ctx, |ui| {
            ui.label("Hello, egui!");
        });
    }
}

Context and Ui

Two core types appear everywhere. egui::Context is the shared, cheaply-cloneable handle to the whole UI state for the frame.

Ui is a region you add widgets into. Panels and windows hand you a &mut Ui inside their closure; you call methods like ui.label or ui.button on it.

egui::CentralPanel::default().show(ctx, |ui| {
    ui.heading("Dashboard");
    ui.separator();
    ui.label("Widgets go here.");
});

Widgets Return Responses

Because the UI is rebuilt each frame, you cannot register callbacks the way retained toolkits do. Instead, every widget call returns a Response immediately.

You inspect the Response in the same frame: .clicked(), .hovered(), .changed(). This keeps event handling inline with layout.

if ui.button("Save").clicked() {
    self.save();
}
let resp = ui.text_edit_singleline(&mut self.name);
if resp.changed() {
    self.dirty = true;
}

State Lives in You

egui stores almost no application data. Your widget values live in self on the App struct, and you pass mutable references into widgets.

A text field takes &mut String; a checkbox takes &mut bool. egui writes back through the reference, so your struct is the single source of truth.

struct MyApp {
    name: String,
    enabled: bool,
}

// inside update:
ui.text_edit_singleline(&mut self.name);
ui.checkbox(&mut self.enabled, "Enabled");

Setting Up eframe

eframe is the official framework that hosts egui on desktop and web. It owns the native window, the GPU surface, and the event loop.

You launch with eframe::run_native, passing a window title, native options, and a closure that builds your App.

fn main() -> eframe::Result<()> {
    let opts = eframe::NativeOptions::default();
    eframe::run_native(
        "My App",
        opts,
        Box::new(|_cc| Ok(Box::new(MyApp::default()))),
    )
}

Repaint Driven by Input

By default egui only repaints when something happens: mouse move, key press, or an explicit request. This saves CPU on idle apps.

For animations or live data, call ctx.request_repaint() to schedule another frame, or request_repaint_after with a duration for timed updates.

ui.label(format!("Tick: {}", self.counter));
self.counter += 1;
ctx.request_repaint(); // keep animating

No Retained Widget IDs (Mostly)

egui derives widget identity from call order and position, generating an Id automatically. This matters for things like collapsing headers that need stable memory between frames.

When two widgets would collide — e.g. buttons with the same label in a loop — wrap them with ui.push_id(i, |ui| ...) to disambiguate.

for (i, item) in self.items.iter().enumerate() {
    ui.push_id(i, |ui| {
        if ui.button(&item.label).clicked() {
            println!("clicked {}", i);
        }
    });
}

Immediate Mode Trade-offs

Immediate mode makes UI code trivially data-driven: an if shows or hides a section, a for renders a list. There is no manual add/remove of nodes and no desync between model and view.

The cost is that the whole UI re-runs each frame, so keep per-frame work cheap and avoid heavy computation inside update.

if self.logged_in {
    ui.label(format!("Welcome, {}", self.user));
} else {
    ui.label("Please sign in.");
}

Minimal Complete App

Putting it together: a struct holds state, update draws it, and main runs the window. This is the entire skeleton of any egui desktop program.

Everything else — layout, theming, packaging — builds on this loop.

#[derive(Default)]
struct App { count: i32 }

impl eframe::App for App {
    fn update(&mut self, ctx: &egui::Context, _: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ctx, |ui| {
            if ui.button("+1").clicked() { self.count += 1; }
            ui.label(format!("Count: {}", self.count));
        });
    }
}

Why Rust Loves egui

egui's design plays to Rust's strengths. Borrowing &mut self into a single update call means the borrow checker guarantees no data races between widgets and your model.

There are no callbacks capturing shared mutable state, no Rc<RefCell> graphs forced by a retained tree — just plain ownership and one mutable pass per frame.

Quick Check

Test your grasp of immediate mode.

Recap

egui is immediate-mode: the whole UI is rebuilt each frame inside eframe::App::update. Widgets are function calls that return a Response you inspect right away.

Your data lives in self and is passed by mutable reference, so the borrow checker keeps model and view in sync. eframe::run_native hosts the window and event loop. Next we explore the widget palette and layout system.

자주 묻는 질문

“즉시 모드 UI 기초” 강의는 무료인가요?

네 — “즉시 모드 UI 기초” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Learn Rust Coding 강의 전체를 잠금 해제할 수 있습니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.

“즉시 모드 UI 기초”에서 뭘 배우나요?

egui가 렌더링하는 방식을 이해해 보세요. 브라우저에서 직접 실행하는 실습 코드로 Learn Rust Coding을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Learn Rust Coding을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Learn Rust Coding은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“즉시 모드 UI 기초” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Learn Rust Coding 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Learn Rust Coding 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 즉시 모드 UI 기초
  2. 위젯과 레이아웃
  3. 앱 상태 관리하기
  4. 데스크톱 앱 패키징하기
← Learn Rust Coding(으)로 돌아가기