小编use*_*625的帖子

迭代器通过引用返回项目,终身问题

我有一个终身问题,我正在尝试实现一个迭代器,通过引用返回它的项目,这里是代码:

struct Foo {
   d: [u8; 42],
   pos: usize
}

impl<'a> Iterator<&'a u8> for Foo {
   fn next<'a>(&'a mut self) -> Option<&'a u8> {
      let r = self.d.get(self.pos);
      if r.is_some() {
         self.pos += 1;
      }
      r
   }
}

fn main() {
   let mut x = Foo {
      d: [1; 42],
      pos: 0
   };

   for i in x {
      println!("{}", i);
   }
}
Run Code Online (Sandbox Code Playgroud)

但是这段代码编译不正确,我得到一个与参数生命周期有关的问题,这里是相应的错误:

$ rustc test.rs
test.rs:8:5: 14:6 error: method `next` has an incompatible type for trait: expected …
Run Code Online (Sandbox Code Playgroud)

iterator reference lifetime rust

12
推荐指数
1
解决办法
1557
查看次数

当特征和类型都不在此包中时提供实现

我想为一个原始类型提供一个特征的实现ToHex(我没有定义serialize)u8:

impl ToHex for u8 {
    fn to_hex(&self) -> String {
        self.to_str_radix(16)
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是我得到这个编译错误:

error: cannot provide an extension implementation where both trait and type are not defined in this crate
Run Code Online (Sandbox Code Playgroud)

我理解这个错误的原因及其逻辑,这是因为特征和原始类型都在我的代码外部.但是我该如何处理这种情况并提供ToHex实现u8呢?更一般地说,你如何处理这类问题,在我看来,这个问题必须是常见的,它应该是可能的,并且很容易扩展这样的类型?

traits rust

7
推荐指数
2
解决办法
2727
查看次数

发送特征的终身问题

我很难理解为什么这段代码无法编译:

use std::cell::{Ref, RefCell};

struct St {
    data: RefCell<uint>
}

impl St {
    pub fn test(&self) -> Ref<uint> {
        self.data.borrow()
    }
}

// This code would compile without T constrained to be Send.
fn func<T: Send>(_: &T) {
}

fn main() {
    let s = St { data: RefCell::new(42) };

    {
        let r7 = s.test();
        // Do not compile
        func(&r7)
    }

    // Compile
    func(&s);
}
Run Code Online (Sandbox Code Playgroud)

它给出以下错误:

bug.rs:21:18: 21:19 error: `s` does not live long enough
bug.rs:21         let r7 = s.test(); …
Run Code Online (Sandbox Code Playgroud)

lifetime send rust

5
推荐指数
1
解决办法
453
查看次数

标签 统计

rust ×3

lifetime ×2

iterator ×1

reference ×1

send ×1

traits ×1