gpt4 book ai didi

arrays - 用于 Rust 结构的实现

转载 作者:行者123 更新时间:2023-11-29 08:25:44 24 4
gpt4 key购买 nike

这段代码有什么问题?

use std::collections::{HashSet,HashMap};
struct Mod_allfun<'r> {
s: HashMap<&'r str, HashSet<&'r str>>
}
impl <'r>Mod_allfun<'r>{
fn new() -> HashMap<&'r str,HashSet<&'r str>> {HashMap::new()}
fn insert(&mut self, c: &'r str, a:&'r [&'r str]){
let aa: HashSet<&'r str>=a.iter().map(|&x| x).collect() ;
self.s.insert( c , aa );
}
}
fn main() {
let z=Mod_allfun::new();
z.insert("str1", ["str2","str3"] );
}

我不知道为什么这不能按预期工作!例如,这确实有效:

use std::collections::{HashSet,HashMap};
fn main() {
let mut mod_allfun: HashMap<& str,HashSet<& str>>= HashMap::new();
let c="str1";
let a=["str2","str3"];
let b = ||{
mod_allfun.insert( c, a.iter().map(|&x| x).collect());
};
}

最佳答案

您从 new 返回一个 HashMap,而不是 Mod_allfun。这确实编译:

use std::collections::{HashSet,HashMap};

struct ModAllfun<'r> {
s: HashMap<&'r str, HashSet<&'r str>>
}

impl<'r> ModAllfun<'r>{
// return a ModAllfun, not a HashMap
fn new() -> ModAllfun<'r> {
ModAllfun { s: HashMap::new() }
}

fn insert(&mut self, c: &'r str, a:&'r [&'r str]){
let aa: HashSet<&'r str> = a.iter().map(|&x| x).collect() ;
self.s.insert(c , aa);
}
}
fn main() {
let mut z = ModAllfun::new();
// pull the array out into a variable to extend its lifetime
let arrs = ["str2","str3"];
z.insert("str1", arrs);
}

关于arrays - 用于 Rust 结构的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26959015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com