我试图做以下几件事
// 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)
}我想要实现的是成功地返回网站结构,而可能没有编辑结构声明。
这是网站结构声明
#[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,
}这是一个错误
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我希望在遇到这个和类似的问题时,能有一个深刻的解释和一般的提示。
发布于 2022-10-25 16:29:53
结构中的&str引用引用read_to_string返回的字符串段。该字符串(hosts_string)在fn get_websites_from_hosts的末尾被删除和解除分配,因此如果您可以返回对它的引用,它们将处于悬空状态。生锈阻止你做那件事。
相反,您需要将read_to_string移出该函数,并将字符串作为&str传入,或者更改您的结构以保存String、IpAddr等拥有的值。
#[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 )。
#[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,
}https://stackoverflow.com/questions/74197284
复制相似问题