设计一个排版引擎其中定义了文档可以包含的类型其中可以让用户自定义使用rust 怎么声明这个类型
在 Rust 中声明一个类型可以使用 struct 关键字,例如:
struct Document {
title: String,
body: String,
author: String,
// ...其他属性
}
如果要让用户自定义文档类型,可以使用泛型,例如:
struct Document<T> {
title: String,
body: T,
author: String,
// ...其他属性
}
这样用户就可以在定义文档时,将自己定义的类型作为 body 属性的类型。例如,如果用户定义了一个 MyType 类型,可以这样使用:
let my_doc = Document {
title: String::from("My Document"),
body: MyType { /*...*/ },
author: String::from("John Doe"),
// ...其他属性
};
原文地址: http://www.cveoy.top/t/topic/8RO 著作权归作者所有。请勿转载和采集!