我想为我的项目创建一个小的图形模块。我需要有向图和无向图。
如果是C++或Java,我会创建一个抽象类图,实现深度优先搜索、广度优先搜索和2个面向特定实现或特定方法的无定向的子类。
我确实读过书中的OOP部分;但是,我如何用特质来表现这种行为呢?
理想情况下,我可以像这样使用我的mod:

use graph::{UndirectedGraph, DirectedGraph, Graph};


pub fn main() {
    let g1 = Undirectedgraph::new(); // implementing Graph trait
    let g2 = DirectedGraph::new(); // implementing Graph trait
    g1.dfs(); // from Graph
    g2.dfs(); // from Graph
    g1.bfs(); // from Graph
    g2.bfs(); // from Graph

    let _ = g1.has_loop(); // from UndirectedGraph implementation only
    let _ = g2.has_loop() // from DirectedGraph implementation only
}


所以我最后得到了这样的结果;正如你所看到的
属性和getter仍然有很多冗余:
#[derive(Debug)]
pub struct Node {
    value: i32,
}

pub trait Graph {
    fn get_vertices(&self) -> &Vec<Node>;

    fn print_nodes(&self) {
        self.get_vertices()
            .iter()
            .for_each(|x| println!("{:#?}", x));
    }

    fn bfs(&self) {
        println!("Common implementation");
    }

    fn dfs(&self) {
        println!("Common implementation");
    }

    fn has_loop(&self) -> bool; // should be implemented
}

pub struct DirectedGraph {
    vertices: Vec<Node>,
}

impl Graph for DirectedGraph {
    fn get_vertices(&self) -> &Vec<Node> {
        &(self.vertices)
    }

    fn has_loop(&self) -> bool {
        //some weird stuff
        // specific to DirectedGraph
        true
    }
}

pub struct UndirectedGraph {
    vertices: Vec<Node>,
}

impl Graph for UndirectedGraph {
    fn get_vertices(&self) -> &Vec<Node> {
        &(self.vertices)
    }

    fn has_loop(&self) -> bool {
        //some weird stuff
        // specific to UndirectedGraph
        true
    }
}

最佳答案

不能直接从特征访问数据的属性(参见Jimmy Cuadra的回答)。但是我们可以使用共享的getter和setter,正如kyle所评论的。
类似下面代码的东西应该可以工作。

trait Graph {
    fn adjacent_edges(&self, v: &Vertex) -> SomeOutput;

    fn dfs(&self, v: &Vertex) -> SomeOutput {
        let adjacent_edges = self.adjacent_edges(v);
        // ...
    }

    fn bfs(&self, v: &Vertex) -> SomeOutput {
        let adjacent_edges = self.adjacent_edges(v);
        // ...
    }
}


struct UndirectedGraph { ... }

impl Graph for UndirectedGraph {
    fn adjacent_edges(&self, v: &Vertex) -> SomeOutput {
        // ...
    }
}


struct DirectedGraph { ... }

impl Graph for DirectedGraph {
    fn adjacent_edges(&self, v: &Vertex) -> SomeOutput {
        // ...
    }
}

07-28 02:11
查看更多