gpt4 book ai didi

Rust:使用通用特征作为特征参数

转载 作者:行者123 更新时间:2023-12-03 11:27:18 25 4
gpt4 key购买 nike

如何在 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
}
}

}


最佳答案

impl<G, GS> TreeNode<GS> where G: Game, GS: GameState<G>{
// ...
}

问题是 G不受约束,因此此块中可能有多个(可能是冲突的)实现,因为 GS也许实现 GameState<G>为多个 G .参数 G是模棱两可的。

如果您想保留GameState<G>能够为多个 G 实现 ,您应该将约束从 impl 移开改为阻止该方法:

// note: G is now a type parameter of the method, not the impl block, which is fine
impl<GS> TreeNode<GS> {
pub fn expand<G>(&mut self, game: &G) where G: Game, GS: GameState<G> {
if !self.expanded{
let child_states = self.data.generate_children(game);
for state in child_states{
self.add_child_with_value(state);
}
}
}
}

如果您只想要 GameState为单个 G 实现 , 你应该做 G GameState 的关联类型而不是泛型类型参数:

trait GameState: std::marker::Sized + Debug {
type G: Game;
fn generate_children(&self, game: &Self::G) -> Vec<Self>;
fn get_initial_state(game: &Self::G) -> Self;
}

// note: now G is given by the GameState implementation instead of
// being a free type parameter
impl<GS> TreeNode<GS> where GS: GameState {
pub fn expand(&mut self, game: &GS::G){
if !self.expanded{
let child_states = self.data.generate_children(game);
for state in child_states{
self.add_child_with_value(state);
}
}
}
}

关于Rust:使用通用特征作为特征参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60766088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com