Jodimoro
Jodimoro

Reputation: 4725

Rust GTK+ example doesn't compile because Option<&str>: From<Option<&String>> is not satisfied

In the Rust GTK examples, there's one called notebook. It doesn't compile:

for i in 1..4 {
    let title = format!("sheet {}", i);
    let label = gtk::Label::new(Some(&title));
    //let label = gtk::Label::new(Some("test1111")); # works well
    notebook.create_tab(&title, label.upcast());
}

The error is:

the trait bound `std::option::Option<&str>: std::convert::From<std::option::Option<&std::string::String>>` is not satisfied

What is it about and how to fix it?

Upvotes: 2

Views: 154

Answers (1)

user4815162342
user4815162342

Reputation: 154926

It seems that you're working with an old copy of gtk-rs/examples. In the current master, the loop in notebook.rs looks like this:

let mut notebook = Notebook::new();

for i in 1..4 {
    let title = format!("sheet {}", i);
    let label = gtk::Label::new(&*title);
    notebook.create_tab(&title, label.upcast());
}

This code compiles - the difference is that it uses &*title to convert a String into something convertible to Option<&str>.

In PR#447, gtk-rs switched from using Option<&str> to Into<Option<&str>> in parameters of functions that accept an optional string, including gtk::Label::new. This made the API more ergonomic, because a constant string argument can be written as "string" instead of Some("string"). However, the change is not 100% backward-compatible - the Into<Option<...>> pattern doesn't support passing Some(&string) with string being an owned String - one must write &*string or the more explicit string.as_str() instead.

Upvotes: 6

Related Questions