如何使用syn插入文档注释?

Mak*_*gan 4 documentation comments rust syn

我有这个小片段试图将注释附加到源文件中。


    let mut file: File = syn::parse_str(file_content.as_str()).expect("Failed to parse Rust code");

    for item in &mut file.items {
        // Use quote! to generate a comment and append it to the item
        let mut comment: Attribute = parse_quote! {
            /// This is a generated comment.
        };

        comment.style = AttrStyle::Outer;

        match item {
            Item::Struct(ref mut s) => {
                s.attrs.push(comment.clone());
            }
            Item::Enum(ref mut e) => {
                e.attrs.push(comment.clone());
            }
            Item::Fn(ref mut f) => {
                f.attrs.push(comment.clone());
            }
            _ => {}
        }
    }
Run Code Online (Sandbox Code Playgroud)

但这是结果:

#[doc = r" This is a generated comment."]
pub struct MTContainerGuardMut<'a, T> {
    data: *mut T,
    #[cfg(debug_assertions)]
    flag: &'a AtomicBool,
    #[cfg(not(debug_assertions))]
    _phantom: PhantomData<&'a ()>,
}
Run Code Online (Sandbox Code Playgroud)

我期待着这种形式的评论/// this is a comment。我究竟做错了什么?

Kev*_*eid 6

/////!从某种意义上说,它们并不是真正的注释:它们是属性的语法糖#[doc]。实际注释在解析时被丢弃,并且不能被 操作syn

因此,您生成的代码是有效的,并将生成文档文本。只是拼写略有不同。