Passing Parameters and Retrieving Data?

I have two questions:

  1. It seems that the program can only be launched using MyApp::run(settings.clone()).unwrap();. I want to pass parameters to an instance of MyApp. How can I do that?
  2. How can I retrieve data from inside the MyApp instance at the end of this function, MyApp::run(settings.clone()).unwrap();?
    I want to access data from within the MyApp instance when this function ends. How can I do this, or is this operation not supported at the moment?

Thank you.

If you are implementing Application rather than Sandbox then you can pass initial values using the Flags generic type in that trait. Here is a little barebones example:

use iced::{Application, Command, Element, widget::text, Settings};

pub struct FlagsExampleApp {
  value: u32,
}

pub struct InputParams {
  initial_value: u32,
}

impl Default for InputParams {
  fn default() -> Self {
    Self{ initial_value: 0 }
  }
}

impl Application for FlagsExampleApp {
  type Executor = iced::executor::Default;
  type Flags = InputParams;
  type Message = ();
  type Theme = iced::Theme;

  fn new(flags: Self::Flags) -> (Self, Command<Self::Message>) {
    // construct initial state from input flags
    let initial_state = Self{ value: flags.initial_value * 2 };
    ( initial_state, Command::none() )
  }

  fn title(&self) -> String {
    String::from("Passing values into app")
  }

  fn update(&mut self, _message: Self::Message) -> Command<Self::Message> {
    Command::none()
  }

  fn view(&self) -> Element<Self::Message> {
    text(format!("Twice the input value is {}", self.value)).into()
  }
}

fn main() {
  // flags input into application
  // typically would use values of command line parameters
  let flags = InputParams{ initial_value: 100 };

  let _ = FlagsExampleApp::run(Settings{ flags, ..Settings::default() });
}

I’m not aware of any way to do this without unsafe code. Initially I thought you’d be able to pass a mutable ref into the application via the flags and update that with whatever return value you wanted but I cannot get this to work. I’m not 100% on the Rust ownership system yet but I think it’s because the application must have static lifetime in the Application::run method so that when it takes ownership of whatever variable you’re trying to return the result in, it takes ownership for the remainder of the program and you cannot access it anymore outside the application.

I might well be wrong though so if anyone has any thoughts, please do chip in.

If the API was to be modified to allow this (assuming it’s not possible at the moment), it might help to know a little more about your usage case.