Anybody here, who's into Rust? Basic question

I’m no developer and have only some very basic knowledge about programming, that I gathered many years ago.

I just started to play around with rust and gtk. And yesterday I was about to pull my hair out while trying to connect two buttons that should change the same entry widget. After hours of reading through examples about ownership and borrowing, I finally put something together that seems to work.

As I stated before, I’m no Dev. Therefore my question is, if anybody here who’s into rust development, could give me a feedback, if the way I got it working is OK or if it is a no go and could be achieved more elegant.

Below follows the code I used to test it:

use glib::clone;
use gtk::prelude::*;
use gtk::{glib, Application, ApplicationWindow, Button, Grid, Entry, EntryBuffer};
const APP_ID: &str = "local.domain.rusttest";

fn main() -> glib::ExitCode {
    // Create a new application
    let app = Application::builder().application_id(APP_ID).build();

    // Connect to "activate" signal of `app`
    app.connect_activate(build_ui);

    // Run the application
    app.run()
}

fn build_ui(app: &Application) {

    // Create an text buffer for the display
    let entry_buffer = EntryBuffer::builder()
        .text("Test")
        .build();

    // Create display
    let entry = Entry::builder()
        .buffer(&entry_buffer)
        .margin_top(12)
        .margin_bottom(12)
        .margin_start(12)
        .margin_end(12)
        .build();


    // Create buttons
    let button_append = Button::builder()
        .label("append")
        .width_request(50)
        .margin_top(12)
        .margin_bottom(12)
        .margin_start(12)
        .margin_end(12)
        .build();

    let button_clear = Button::builder()
        .label("clear")
        .width_request(50)
        .margin_top(12)
        .margin_bottom(12)
        .margin_start(12)
        .margin_end(12)
        .build();

    // Create a grid container that holds the buttons
    let grid= Grid::new();


    grid.attach(&entry, 0, 0, 2, 1);

    grid.attach(&button_append, 0, 1, 1, 1);
    grid.attach(&button_clear, 1, 1, 1, 1);
   

    // Create a window
    let window = ApplicationWindow::builder()
        .application(app)
        .title("RustTest")
        .child(&grid)
        .build();

    // Connect to "clicked" signal of `button`
    button_append.connect_clicked(clone!(@weak entry => move |_| {
        change_entry(&entry, "append");
    }));

    button_clear.connect_clicked(clone!(@weak entry => move |_| {
        clear_entry(&entry);
    }));

    // Present window
    window.present();
}

fn change_entry(entry: &Entry, s: &str) {
    let mut t = entry.text().to_string();
    let s = s.to_string();
    t.push_str(&s);
    entry.set_text(t.as_str());
}

fn clear_entry(entry: &Entry) {
    entry.set_text("");
}



1 Like