【问题标题】:Can I put field bounds on a template type in Rust?我可以在 Rust 中的模板类型上设置字段边界吗?
【发布时间】:2022-06-22 23:08:06
【问题描述】:

在 rust 中,我可以在模板参数上设置 trait bound,以保证它符合我想要的功能:

fn print<T:Debug>(t: T) {
    println!("{:?}", t);
}

我可以对字段做类似的事情吗?

fn print_name<T:HasNameField>(t: T) {
    println!("{:?}", t.name);
}

我的用例是在 yew 中我想创建一个表单。而不仅仅是使用&lt;input type="text".../&gt;,我希望用户能够创建自己的输入字段并能够构建CustomForm。然后我可以:

#[function_component(CustomForm)]
fn custom_form<T: yew::Component>() -> Html {
    <form>
        <T name="field name"/>
    </form>
}

目前此操作失败并显示以下消息:

error[E0609]: no field `name` on type `<T as yew::Component>::Properties`

【问题讨论】:

    标签: rust yew


    【解决方案1】:

    从 Rust 1.62.0 (2022-06-30) 开始,特征不能需要字段。 不过,您可以改用函数。

    trait Named {
        fn get_name(&self) -> &str;
    }
    

    然后,只需像其他任何 trait 一样实现它。

    struct NameImpl;
    
    impl Named for NameImpl {
        fn get_name(&self) -> &str {
            "my field name"
        }
    }
    

    您可以将其用作类型绑定,并随意调用get_name()

    fn do_stuff_with_named<N: Named>(n: N) {
        println!("{}", n.get_name())
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-17
      • 2014-09-20
      • 2020-08-17
      • 2011-04-04
      • 2011-09-30
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多