我有一个Option<&mut T>
并且想要多次访问包含的引用,如下所示:
fn f(a: Option<&mut i32>) {
if let Some(x) = a {
*x = 6;
}
// ...
if let Some(x) = a {
*x = 7;
}
}
fn main() {
let mut x = 5;
f(Some(&mut x));
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为if let Some(x) = a
将参考值移出Option,第二个if let Some(x) = a
将导致编译器错误.没有第二个if let ...
,这完美无缺,所以a
不必是可变的.
下列:
if let Some(ref x) = a {
**x = 6;
}
Run Code Online (Sandbox Code Playgroud)
给出错误:"赋值给不可变引用".
这可行:
fn f(mut a: Option<&mut …
Run Code Online (Sandbox Code Playgroud) 例如:
struct T(u32); // No Copy implementation
fn consume(t: T) {}
fn main() {
let v = vec![T(1), T(2)];
let s = v.into_boxed_slice();
// Get a Box<[T]> from somewhere and consume it:
for t in s {
consume(t);
}
}
Run Code Online (Sandbox Code Playgroud)
结果编译器错误:
struct T(u32); // No Copy implementation
fn consume(t: T) {}
fn main() {
let v = vec![T(1), T(2)];
let s = v.into_boxed_slice();
// Get a Box<[T]> from somewhere and consume it:
for t in s {
consume(t);
}
} …
Run Code Online (Sandbox Code Playgroud) 我想将 u64 值转换为通用数字类型,例如
fn f<T: AppropriateTrait>(v: u64) -> T {
v as T
}
Run Code Online (Sandbox Code Playgroud)
并让它在语义上表现得像,例如,259u64 as u8
即,它应该只采用最低有效位。不幸的是,如果输入值不适合,该FromPrimitive::from_u64
函数将返回 , with 。Option<T>
None
这在这里有效:
fn f<T: FromPrimitive + Int + ToPrimitive>(v: u64) -> T {
T::from_u64(v & T::max_value().to_u64().unwrap()).unwrap()
}
Run Code Online (Sandbox Code Playgroud)
但它非常冗长且不优雅。有没有更好的办法?
编辑:我只对转换为整数类型感兴趣,例如 u8、u16 等,没有什么时髦的东西。
我想实现一个特质Foo
的Iterator
(即,为实现所有类型Iterator
),所以我写了这一点:
trait Foo {
fn foo(&self);
}
impl<F, FI> Foo for FI
where F: Foo,
FI: Iterator<Item=F> + Clone,
{
fn foo(&self) {
// Just for demonstration
for x in self.clone() {
x.foo();
}
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,它编译.但是,当我另外实现Foo
另一种类型时,比如
impl Foo for u32 {
fn foo(self) { println!("{} u32", self); }
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误消息:
t.rs:5:1: 7:2 error: conflicting implementations for trait `Foo` [E0119]
t.rs:5 impl Foo for u32 {
t.rs:6 fn foo(self) { println!("{} u32", …
Run Code Online (Sandbox Code Playgroud) rust ×4