首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从铁锈中的函数返回其属性具有&str类型的结构?

如何从铁锈中的函数返回其属性具有&str类型的结构?
EN

Stack Overflow用户
提问于 2022-10-25 16:24:41
回答 1查看 31关注 0票数 0

我试图做以下几件事

代码语言:javascript
复制
// Just removes redundant white space while also splitting the string
// with a whitespace.
fn split_whitespace(string: &str) -> Vec<&str> {
    let words: Vec<&str> = string
        .split_whitespace()
        .filter(|&word| word != "")
        .collect();
    words
}

pub fn get_websites_from_hosts(hosts_path: &Path) -> Result<Vec<Website>, std::io::Error> {
    let hosts_string = read_to_string(hosts_path)?;

    let result: Vec<Website> = hosts_string
        .lines()
        .filter(|&line| split_whitespace(&line.to_owned()).len() == 2)
        .map(|line| {
            let ip_domain = split_whitespace(&line.to_owned());
            Website {
                domain_name: ip_domain[1], // This won't work because it is refering hosts_string which is a local variable of the function
                redirect_ip: ip_domain[0], // the same case with this one.
                is_blocked: true,
                hosts_path,
            }
        })
        .collect();

    Ok(result)
}

我想要实现的是成功地返回网站结构,而可能没有编辑结构声明。

这是网站结构声明

代码语言:javascript
复制
#[derive(Debug, Clone)]
pub struct Website<'a> {
    pub domain_name: &'a str,
    pub redirect_ip: &'a str,
    pub is_blocked: bool,
    pub hosts_path: &'a Path,
}

这是一个错误

代码语言:javascript
复制
error[E0515]: cannot return value referencing temporary value
  --> src/parser.rs:21:13
   |
20 |               let ip_domain = split_whitespace(&line.to_owned());
   |                                                 --------------- temporary value created here
21 | /             Website {
22 | |                 domain_name: ip_domain[1],
23 | |                 redirect_ip: ip_domain[0],
24 | |                 is_blocked: true,
25 | |                 hosts_path,
26 | |             }
   | |_____________^ returns a value referencing data owned by the current function

For more information about this error, try `rustc --explain E0515`.
error: could not compile `website-blocker` due to previous error
warning: build failed, waiting for other jobs to finish...
error: could not compile `website-blocker` due to previous error

我希望在遇到这个和类似的问题时,能有一个深刻的解释和一般的提示。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-25 16:29:53

结构中的&str引用引用read_to_string返回的字符串段。该字符串(hosts_string)在fn get_websites_from_hosts的末尾被删除和解除分配,因此如果您可以返回对它的引用,它们将处于悬空状态。生锈阻止你做那件事。

相反,您需要将read_to_string移出该函数,并将字符串作为&str传入,或者更改您的结构以保存StringIpAddr等拥有的值。

代码语言:javascript
复制
#[derive(Debug, Clone)]
pub struct Website<'a> {
    pub domain_name: String,
    pub redirect_ip: IpAddr,
    pub is_blocked: bool,
    pub hosts_path: &'a Path,
}

如果要避免某些String分配,可以使用“小字符串优化”库(如compact_str )。

代码语言:javascript
复制
#[derive(Debug, Clone)]
pub struct Website<'a> {
    // Stores a domain name of up to 24 bytes in place,
    // without an extra heap allocation
    pub domain_name: CompactString,
    pub redirect_ip: IpAddr,
    pub is_blocked: bool,
    pub hosts_path: &'a Path,
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74197284

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档