我有这个小片段,试图将注释附加到源文件中。
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());
}
_ => {}
}
}
但这就是结果:
#[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 ()>,
}
我期待着
/// this is a comment
形式的评论。我做错了什么?
///
和//!
并不是真正的注释:它们是#[doc]
属性的语法糖。实际注释在解析时会被丢弃,并且不能被
syn
操作。因此,您生成的代码是有效的,并将生成文档文本。只是拼写有点不同。