【问题标题】:Why this error? Cannot we use format macro inside function parenthesis?为什么会出现这个错误?我们不能在函数括号内使用格式宏吗?
【发布时间】:2021-06-05 20:18:18
【问题描述】:

代码:

fltk::frame::Frame::new(0,0, 300, 100, format!("side item {}", i));

输出错误:

the trait `std::convert::From<std::string::String>` is not implemented for `std::option::Option<&'static str>`

【问题讨论】:

    标签: rust rust-cargo fltk


    【解决方案1】:

    这几乎意味着您只能使用字符串文字。所以不,你不能直接使用format!()。似乎 FLTK 不打算以这种方式使用动态分配的字符串。

    使用Box::leak 可以解决此问题。但请注意,它会按照它在锡上所说的那样做——它会泄漏内存,除非你在小部件被销毁后通过Box::from_raw() 回收它。

    let leaked_title = &*Box::leak(format!("abc {}", 1).into_boxed_str())
    fltk::frame::Frame::new(0,0, 300, 100, leaked_title);
    

    【讨论】:

      【解决方案2】:

      默认 ::new 构造函数需要Into&lt;Option&lt;&amp;'static str&gt;&gt;,因此如果您的&amp;str 不是静态的,您可以使用with_label()set_label()

      fltk::frame::Frame::new(0,0, 300, 100, None).with_label(&format!("side item {}", i));
      

      let mut my_frame = fltk::frame::Frame::new(0,0, 300, 100, None);
      my_frame.set_label(&format!("side item {}", i));
      

      【讨论】:

      • 看起来比我的解决方案更好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多