use std::collections::HashMap;
#[derive(Clone,Debug)]
pub enum Address {
Ptr(Box<Node>),
None,
}
#[derive(Clone,Debug)]
pub struct Node {
connection: String,
value: i32,
next: Address,
}
impl Node {
pub fn new(connection:String, value: i32) -> Node{
Node{
connection,
value,
next: Address::None,
}
}
pub fn insert(&mut self, connection: String, value: i32) {
match self.next {
Address::Ptr(ref mut v) => {
v.insert(connection,value);
}
Address::None => {
self.next = Address::Ptr(Box::new(Node{connection,value,next:Address::None}))
}
}
}
}
struct GraphAdj {
vec_edge: HashMap<String,Node>
}
impl GraphAdj {
pub fn new() -> GraphAdj{
GraphAdj{
vec_edge: HashMap::new(),
}
}
pub fn insert(&mut self, value: String) -> Result<(),String> {
if self.vec_edge.contains_key(&value) {
return Err(format!("Key already present"))
}
self.vec_edge.insert(value,
Node::new(String::from(""),-1)
);
Ok(())
}
pub fn add_connection(&mut self,
source_vertex: String,
destination_vertex: String,
cost: i32,
){
for (key,value) in self.vec_edge.iter_mut() {
if *key == source_vertex {
value.insert(destination_vertex,cost);
}
}
}
}
fn main(){}
我遇到了以下错误。
***cargo check
Checking rust_graph v0.1.0 (D:\projects\DSA\graph\rust_graph)
error[E0382]: use of moved value: `destination_vertex`
--> src\main.rs:36:30
|
30 | destination_vertex: String,
| ------------------ move occurs because `destination_vertex` has type `String`, which does not implement the `Copy` trait
...
36 | value.insert(destination_vertex,cost);
| ^^^^^^^^^^^^^^^^^^ value moved here, in previous iteration of loop
error: aborting due to previous error***
***For more information about this error, try `rustc --explain E0382`.
error: could not compile `rust_graph`
To learn more, run the command again with --verbose.***
我知道String变量被移动了,但为什么这是个问题呢?我的意思是我之后也不会再使用它了。
clone()
目标顶点:value.insert(destination_vertex.clone(), cost)
。由于Node::insert
接受一个拥有所有权的String
,所以你必须提供一个克隆版本,否则无法绕过这个问题。 - user4815162342key
是唯一的,则在插入值后可以使用break
或return
。否则,就像@user4815162342所说,您需要克隆destination_vertex
,以便在未来的迭代中保留副本。 - Jmbinsert()
可以使用引用,但仍然必须创建一个真正的String
来创建一个Node
。因此,它要么必须创建一个拥有的字符串(相当于要求调用者进行clone()
),要么您需要更改Node
以存储引用,这将需要将生命周期信息附加到Node
并确保Node
不会超出字符串的生命周期。换句话说,在那里几乎肯定 不 想使用引用。 - user4815162342