相关疑难解决方法(0)

返回本地String作为选项<&str>

我想编写一个接收&str参数并返回的函数Option<&str>.我写了这个:

fn f(text: &str) -> Option<&str> {
    if // some condition {
        return None;
    }

    let mut res = String::new();
    // write something into res.

    // return res
    Some(&res[..])
}
Run Code Online (Sandbox Code Playgroud)

但是我收到一个错误:

res 活得不够久.

解决这个问题的最佳解决方案是什么?

rust

0
推荐指数
1
解决办法
454
查看次数

无法将字符串拆分为具有显式生存期的字符串切片,因为字符串的活动时间不够长

我正在写一个应该从实现BufRead特性的东西中读取的库; 网络数据流,标准输入等.第一个函数应该从该读取器读取数据单元并返回一个填充的结构,该结构主要填充有&'a str从线路中的帧解析的值.

这是一个最小版本:

mod mymod {
    use std::io::prelude::*;
    use std::io;

    pub fn parse_frame<'a, T>(mut reader: T)
    where
        T: BufRead,
    {
        for line in reader.by_ref().lines() {
            let line = line.expect("reading header line");
            if line.len() == 0 {
                // got empty line; done with header
                break;
            }
            // split line
            let splitted = line.splitn(2, ':');
            let line_parts: Vec<&'a str> = splitted.collect();

            println!("{} has value {}", line_parts[0], line_parts[1]);
        }
        // more reads down here, therefore the reader.by_ref() above …
Run Code Online (Sandbox Code Playgroud)

rust

0
推荐指数
1
解决办法
553
查看次数

使用“insert_str”时,为什么返回空元组而不是带有生命周期注释的可变字符串切片?

我无法理解以下功能有什么问题。

fn percuss<'a>(a: &'a mut str, b: &str, val: usize) -> &'a mut str {
    a.to_string().insert_str(val, b)
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误:

error[E0308]: mismatched types
 --> src/lib.rs:2:5
  |
2 |     a.to_string().insert_str(val, b)
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `&mut str`, found `()`
Run Code Online (Sandbox Code Playgroud)

我没有或没有看到任何a.to_string().insert_str(val, b)退货的理由()。有人可以阐明我缺少注意/理解的内容吗?

rust

0
推荐指数
1
解决办法
384
查看次数

无法返回Chars迭代器,因为它"活不够久"

我希望能够将一个Chars迭代器分配给一个结构,String该结构是在struct的"constructor"方法中创建的.我该怎么做呢?

代码(运行它):

use std::str::Chars;

fn main() {
    let foo = Foo::new();
}

struct Foo<'a> {
    chars: Chars<'a>
}
impl<'a> Foo<'a> {
    pub fn new() -> Self {
        let s = "value".to_string();
        Foo { chars: s.chars() }
    }
}
Run Code Online (Sandbox Code Playgroud)

错误:

error: `s` does not live long enough
  --> <anon>:13:22
13 |>         Foo { chars: s.chars() }
   |>                      ^
note: reference must be valid for the lifetime 'a as defined on the block at 11:25...
  --> …
Run Code Online (Sandbox Code Playgroud)

rust

-2
推荐指数
1
解决办法
112
查看次数

标签 统计

rust ×4