如何在Rust中使用相关的泛型类型?
这是我所拥有的(只有第一行给我带来麻烦):
impl<G, GS> TreeNode<GS> where G: Game, GS: GameState<G>{
pub fn expand(&mut self, game: &G){
if !self.expanded{
let child_states = self.data.generate_children(game);
for state in child_states{
self.add_child_with_value(state);
}
}
}
}
GameState
是Game
的通用特征,self.data
实现此类型的GameState<Game>
。编译器告诉我
error[E0207]: the type parameter `G` is not constrained by the impl trait, self type, or predicates
--> src/mcts.rs:42:6
|
42 | impl<G, GS> TreeNode<GS> where G: Game, GS: GameState<G>{
| ^ unconstrained type parameter
error: aborting due to previous error
但是在我看来,我既要在G
函数中约束expand
,又要限制G
必须属于GS
。我将非常感谢您的帮助。
编辑:到目前为止,这里还有更多的定义
trait GameState<G: Game>: std::marker::Sized + Debug{
fn generate_children(&self, game: &G) -> Vec<Self>;
fn get_initial_state(game: &G) -> Self;
}
trait Game{}
struct TreeNode<S> where S: Sized{
parent: *mut TreeNode<S>,
expanded: bool,
pub children: Vec<TreeNode<S>>,
pub data: S,
pub n: u32
}
impl<S> TreeNode<S>{
pub fn new(data: S) -> Self{
TreeNode {
parent: null_mut(),
expanded: false,
children: vec![],
data,
n: 0
}
}
pub fn add_child(&mut self, mut node: TreeNode<S>){
node.parent = self;
self.children.push(node);
}
pub fn add_child_with_value(&mut self, val: S){
let new_node = TreeNode::new(val);
self.add_child(new_node);
}
pub fn parent(&self) -> &Self{
unsafe{
&*self.parent
}
}
}
G
的类型确定TreeNode<GS>
的具体类型;仅在调用expand
时才知道。请注意,对于expand
,可以使用different