【问题标题】:How to set generic trait as type of function argument?如何将通用特征设置为函数参数的类型?
【发布时间】:2016-01-28 14:38:16
【问题描述】:

有通用特征Graph

type NodeKey = usize;
type EdgeWeight = usize;

trait Graph<T> {
    fn add_node(&mut self, node: T) -> NodeKey;
    fn add_edge(&mut self, begin: NodeKey, end: NodeKey, weight: EdgeWeight);
    fn new() -> Self;
}

及其实现AdjacencyListstruct

struct AdjacencyList<T> {
    // ...
}
impl<T> Graph<T> for AdjacencyList<T> {
    // ...
}

我需要一个函数,它接受一个空图并对其进行处理。

fn create_sample_graph<T: Graph<&'static str>>(graph: &mut T) {
    let key1 = graph.add_node("node1");
    // ...
}

我使用&amp;str 类型创建AdjacencyList 的实例并将其发送到函数。

fn main() {
    let mut adjacency_list = AdjacencyList::<&str>::new();
    create_sample_graph(adjacency_list);
}

但编译器失败并出现以下错误:

error: mismatched types:
 expected `&mut _`,
    found `AdjacencyList<&str>`
(expected &-ptr,
    found struct `AdjacencyList`) [E0308]
create_sample_graph(adjacency_list);
                    ~~~~~~~~~~~~~~

如何将 trait 设置为函数参数的类型并传递一个实现该 trait 的结构?

【问题讨论】:

    标签: generics struct rust traits


    【解决方案1】:

    您需要传递&amp;mut adjacency_list。这就是错误的意思,而且是正确的:您已将函数定义为采用 &amp;mut 指针,但您直接传递值。

    【讨论】:

    • 是的。你说的对!我是 rust 的初学者,他的所有权规则对我来说并不明显。因此,我经常寻找错误问题的答案。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2014-05-31
    • 1970-01-01
    • 2022-06-16
    • 2012-01-14
    相关资源
    最近更新 更多