代码之家  ›  专栏  ›  技术社区  ›  Tim Diekmann suresh madaparthi

除了新的关键字之外,原始标识符的用例是什么?

  •  3
  • Tim Diekmann suresh madaparthi  · 技术社区  · 6 年前

    raw identifiers 以下内容:

    try 函数,要在Rust 2018中调用它,您需要使用原始标识符。

    type r#type ty

    2 回复  |  直到 6 年前
        1
  •  4
  •   Lukas Kalbertodt    6 年前

    r#type ty

    "type": 27,
    

    #[derive(Serialize)]
    struct Foo {
        r#type: u32,
    }
    

    另一方面。。。塞尔德已经有了一种方法来实现你想要的: the #[serde(rename = "name")] attribute

    #[derive(Serialize)]
    struct Foo {
        #[serde(rename = "type")]
        ty: u32,
    }
    

    同样地, Debug Foo { type: 27 }

    #[derive(Debug)]
    struct Foo {
        r#type: u32,
    }
    

    调试

    impl fmt::Debug for Foo {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            f.debug_struct("Foo")
                .field("type", &self.ty)
                .finish()
        }
    }
    

    所以在实践中,我不明白为什么要使用原始标识符,因为您必须使用 r#

    不过,拥有这样的语法“只为案例”是一件好事。

        2
  •  0
  •   ljedrz    6 年前

    raw_identifiers 你可以用 type

    #![feature(rust_2018_preview)]
    #![feature(raw_identifiers)]
    
    struct r#let {} // just warnings: struct is never used: `let` and type `let` should have a camel case name such as `Let`
    
    fn main() {
        let r#type = 0; // just warning: unused variable: `type`
    }
    

    但是,它不适用于每个关键字:

    let r#super = 0; // error: `r#super` is not currently supported.
    
    推荐文章