相关疑难解决方法(0)

为什么我不能在同一个结构中存储值和对该值的引用?

我有一个值,我想在我自己的类型中存储该值以及对该值内部内容的引用:

struct Thing {
    count: u32,
}

struct Combined<'a>(Thing, &'a u32);

fn make_combined<'a>() -> Combined<'a> {
    let thing = Thing { count: 42 };

    Combined(thing, &thing.count)
}
Run Code Online (Sandbox Code Playgroud)

有时候,我有一个值,我想在同一个结构中存储该值和对该值的引用:

struct Combined<'a>(Thing, &'a Thing);

fn make_combined<'a>() -> Combined<'a> {
    let thing = Thing::new();

    Combined(thing, &thing)
}
Run Code Online (Sandbox Code Playgroud)

有时,我甚至没有参考该值,我得到同样的错误:

struct Combined<'a>(Parent, Child<'a>);

fn make_combined<'a>() -> Combined<'a> {
    let parent = Parent::new();
    let child = parent.child();

    Combined(parent, child)
}
Run Code Online (Sandbox Code Playgroud)

在每种情况下,我都会收到一个错误,即其中一个值"活不够长".这个错误是什么意思?

lifetime rust borrow-checker

193
推荐指数
3
解决办法
2万
查看次数

返回迭代器(或任何其他特征)的正确方法是什么?

以下Rust代码编译并运行没有任何问题.

fn main() {
    let text = "abc";
    println!("{}", text.split(' ').take(2).count());
}
Run Code Online (Sandbox Code Playgroud)

在那之后,我尝试了类似的东西....但它没有编译

fn main() {
    let text = "word1 word2 word3";
    println!("{}", to_words(text).take(2).count());
}

fn to_words(text: &str) -> &Iterator<Item = &str> {
    &(text.split(' '))
}
Run Code Online (Sandbox Code Playgroud)

主要问题是我不确定函数to_words()应该具有什么返回类型.编译器说:

error[E0599]: no method named `count` found for type `std::iter::Take<std::iter::Iterator<Item=&str>>` in the current scope
 --> src/main.rs:3:43
  |
3 |     println!("{}", to_words(text).take(2).count());
  |                                           ^^^^^
  |
  = note: the method `count` exists but the following trait bounds were not satisfied:
          `std::iter::Iterator<Item=&str> : std::marker::Sized`
          `std::iter::Take<std::iter::Iterator<Item=&str>> …
Run Code Online (Sandbox Code Playgroud)

rust

92
推荐指数
1
解决办法
2万
查看次数

我可以编写一个自我变异的迭代器,然后产生一个引用吗?

我遇到了一个简化为以下问题的问题:

struct MyIter {
    vec: Vec<i8>,
}

fn fill_with_useful_data(v: &mut Vec<i8>) {
    /* ... */
}

impl<'a> Iterator for MyIter {
    type Item = &'a [i8];

    fn next(&mut self) -> Option<&'a [i8]> {
        fill_with_useful_data(&mut self.vec);

        Some(&self.vec)
    }
}

fn main() {
    for slice in (MyIter { vec: Vec::new() }) {
        println!("{}", slice);
    }
}
Run Code Online (Sandbox Code Playgroud)

这会生成错误:

error[E0207]: the lifetime parameter `'a` is not constrained by the impl trait, self type, or predicates
 --> src/main.rs:9:6
  |
9 | impl<'a> Iterator for MyIter …
Run Code Online (Sandbox Code Playgroud)

rust

11
推荐指数
1
解决办法
1055
查看次数

如何将 Chars 迭代器存储在与它正在迭代的 String 相同的结构中?

我刚刚开始学习 Rust,我正在努力处理生命周期。

我想要一个带有 a 的结构String,它将用于缓冲来自 stdin 的行。然后我想在结构上有一个方法,它从缓冲区返回下一个字符,或者如果该行中的所有字符都已被消耗,它将从标准输入读取下一行。

文档说 Rust 字符串不能按字符索引,因为 UTF-8 效率低下。当我按顺序访​​问字符时,使用迭代器应该没问题。但是,据我所知,Rust 中的迭代器与它们正在迭代的事物的生命周期相关联,我无法弄清楚如何将这个迭代器与String.

这是我想要实现的伪 Rust。显然它不会编译。

struct CharGetter {
    /* Buffer containing one line of input at a time */
    input_buf: String,
    /* The position within input_buf of the next character to
     * return. This needs a lifetime parameter. */
    input_pos: std::str::Chars
}

impl CharGetter {
    fn next(&mut self) -> Result<char, io::Error> {
        loop {
            match self.input_pos.next() {
                /* If there is still a character left in …
Run Code Online (Sandbox Code Playgroud)

rust

9
推荐指数
1
解决办法
2428
查看次数

是否拥有String :: chars的所有版本?

以下代码无法编译:

use std::str::Chars;

struct Chunks {
    remaining: Chars,
}

impl Chunks {
    fn new(s: String) -> Self {
        Chunks {
            remaining: s.chars(),
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

错误是:

use std::str::Chars;

struct Chunks {
    remaining: Chars,
}

impl Chunks {
    fn new(s: String) -> Self {
        Chunks {
            remaining: s.chars(),
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Chars不拥有要迭代的字符,也不能超过其&strString从其创建的字符。

是否存在Chars不需要生存期参数的私有版本,或者我必须自己保留Vec<char>和索引?

string iterator ownership rust

5
推荐指数
3
解决办法
632
查看次数

标签 统计

rust ×5

borrow-checker ×1

iterator ×1

lifetime ×1

ownership ×1

string ×1