Rust GTK +示例无法编译,因为不满足选项<&str>:From <Option <&String >>

Jod*_*oro 2 gtk rust

Rust GTK的例子中,有一个叫做笔记本.它不编译:

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());
}
Run Code Online (Sandbox Code Playgroud)

错误是:

the trait bound `std::option::Option<&str>: std::convert::From<std::option::Option<&std::string::String>>` is not satisfied
Run Code Online (Sandbox Code Playgroud)

它是什么以及如何解决它?

use*_*342 6

看来你正在使用旧的副本gtk-rs/examples.在当前的master中,循环notebook.rs如下所示:

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());
}
Run Code Online (Sandbox Code Playgroud)

这段代码编译 - 不同之处在于它用于&*title转换String为可转换为的东西Option<&str>.

PR#447中,gtk-rs从使用切换Option<&str>Into<Option<&str>>接受可选字符串的函数的参数,包括gtk::Label::new.这使得API更符合人体工程学,因为可以将常量字符串参数写为"string"而不是Some("string").然而,这种变化是不是100%的向后兼容-该Into<Option<...>>模式不支持将Some(&string)string作为一个拥有String-一个必须编写&*string或更明确的string.as_str()来代替.