Tom*_*wor 0 rust data-structures
我正在创建表示图中边的简单通用结构,并且我希望构造函数切换参数,因此较低的将是第一个。
pub type Index = u16;
pub type Cost = u32;
pub struct Edge<T> {
first: Index,
second: Index,
weight: T,
}
impl<T> Edge<T> {
pub fn new(first: Index, second: Index, weight: T) -> Self {
return if second > first {
Edge { second, first, weight }
} else {
Edge { first, second, weight }
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是我无法使它工作,因为我的测试导致错误。
#[test]
fn should_initialize_with_lover_value_first() {
// given
let lower: Index = 234;
let high: Index = 444;
let cost: Cost = 34;
// when
let edge: Edge<Cost> = Edge::new(high, lower, cost);
// then
assert_eq!(edge.first, lower, "edge.first = {}, expected = {}", edge.first, lower);
assert_eq!(edge.second, high, "edge.second = {}, expected = {}", edge.second, high);
}
Run Code Online (Sandbox Code Playgroud)
我有错误:
thread 'types::generic::edge::tests::should_initialize_with_lover_value_first' panicked at 'assertion failed: `(left == right)`
left: `444`,
right: `234`: edge.first = 444, expected = 234', src/types/generic/edge.rs:35:9
Run Code Online (Sandbox Code Playgroud)
我是否错过了某种我不知道的奇怪的生锈行为?
当变量名称与字段名称相同时,Rust 允许您对变量名称进行双关语。所以这:
Edge { second, first, weight }
Run Code Online (Sandbox Code Playgroud)
相当于:
Edge {
second: second,
first: first,
weight: weight,
}
Run Code Online (Sandbox Code Playgroud)
和这个:
Edge { first, second, weight }
Run Code Online (Sandbox Code Playgroud)
相当于:
Edge {
first: first,
second: second,
weight: weight,
}
Run Code Online (Sandbox Code Playgroud)
如您所见,它们彼此等效。
如果你想翻转first和second那么你就可以做到这一点,而不是:
Edge {
first: second,
second: first,
weight,
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53 次 |
| 最近记录: |