Sign up

Defining event handlers

Is there any way of not specifying parameters in D for closures being used for callbacks when the parameters are not used. Rust does this very well by using _ and requiring the compiler to do all the needed type inference.

Here is adding an application menu in D:

application.addOnStartup(delegate void(GioApplication app) {
		auto menuBuilder = new Builder();
		if (menuBuilder.addFromString(import("application_menu.xml"))) {
			auto a = cast(Application) app;
			a.setAppMenu(cast(MenuModel) menuBuilder.getObject("application_menu"));
			auto aboutAction = new SimpleAction("about", null);
			aboutAction.addOnActivate(delegate void(Variant v, SimpleAction sa){});
			a.addAction(aboutAction);
			auto quitAction = new SimpleAction("quit", null);
			quitAction.addOnActivate(delegate void(Variant v, SimpleAction sa){ a.quit(); });
			a.addAction(quitAction);
		} else {
			writeln("Couldn't get the application menu.");
		}
	});

here is the same code in Rust:

    application.connect_startup(|app|{
        let menu_builder = gtk::Builder::new_from_string(include_str!("resources/application_menu.xml"));
        let application_menu = menu_builder.get_object::<gio::Menu>("application_menu").expect("Could not construct the application menu.");
        app.set_app_menu(&application_menu);
        let about_action = gio::SimpleAction::new("about", None);
        about_action.connect_activate(move |_, _| about::present(None));
        app.add_action(&about_action);
        let quit_action = gio::SimpleAction::new("quit", None);
        quit_action.connect_activate({let a = app.clone(); move |_, _| a.quit()});
        app.add_action(&quit_action);
    });

Re: Defining event handlers

On 21-10-17 12:33, Russel Winder wrote:

Is there any way of not specifying parameters in D for closures being used for callbacks when the parameters are not used. Rust does this very well by using _ and requiring the compiler to do all the needed type inference.

You could take advantage of D's type inference and use _ as a variable name:

quitAction.addOnActivate((_, __){ a.quit(); });

Only D doesn't allow you to use the same name for two parameters.

Re: Defining event handlers

Aha, excellent.

Of course, it is almost certain that I should have already known that. :-)

Thanks Mike, much appreciated.