小编Adr*_*her的帖子

多次阅读Option <&mut T>中的参考文献

我有一个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)

rust

8
推荐指数
1
解决办法
167
查看次数

如何将元素移出装箱切片,并在此过程中消耗该切片?

例如:

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)

rust

8
推荐指数
1
解决办法
2842
查看次数

如何将 u64 值转换为通用数字类型?

我想将 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 等,没有什么时髦的东西。

rust

3
推荐指数
1
解决办法
1772
查看次数

实现Iterator + Clone的特征:冲突的实现

我想实现一个特质FooIterator(即,为实现所有类型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

3
推荐指数
1
解决办法
167
查看次数

标签 统计

rust ×4