【发布时间】:2022-10-17 00:35:52
【问题描述】:
我正在尝试使用一个结构而不初始化它的一些成员,以便能够使用它:
struct Structure {
initialized: bool,
data: StructureData, // This is another struct...
target: TargetTrait, // This member that I don't need to initialize.
}
impl Structure {
pub fn initialize(&mut self) -> bool {
if self.initialized {
false
} else {
// Here I should initialize the target...
self.target = initializeTarget(...); // No problem...
self.initialized = true;
true
}
}
pub fn new(&self) -> Structure {
Structure {
initialized: false, // The initialize method will do that...
data: StructureData, // Initializing Structure data behind the
// scenes...
// Here the struct needs some value for the target, but I cannot provide any value,
// Because the initialization method will do that job...
target: None, // I tried using (None), and Option<T>,.
// But the TargetTrait refused.
}
}
}
// main function:
fn main() {
let structure: Structure = Structure::new(); // It should construct a new structure...
if structure.initialize() {
// Here, I should do some work with the target...
}
}
我尝试使用 Option,但目标 trait 没有实现 Option,甚至没有实现
#[derive(Default)]
【问题讨论】:
-
目标特征是什么意思?如果您受到某个特征的限制,而这正是您提出问题的真正原因,那么也请在您的问题中包含该特征。
-
@Peter Hall,该特征是一个外部库!
标签: rust struct initialization member