我还是Rust的另一个初学者,在我的类型之间进行转换时遇到困难。归结为我有一个HashMap<String, Type>
和&[Type]
作为另一个函数的输入。
不需要快速或高效,因此,优雅的解决方案比高效的解决方案更为可取。
我的HashMap位于名为“ parsed_result”的变量中,我试图将其转换为这样:
let mut secs: Vec<_> = parsed_result.values().map(|ms|ms.clone()).collect();
let mem_map = mem_planner::plan1(&secs);
但是,我仅收到以下编译错误。
error[E0308]: mismatched types
--> src\main.rs:17:38
|
17 | let mem_map = mem_planner::plan1(&secs);
| ^^^^^ expected slice, found struct `std::vec::Vec`
|
= note: expected type `&[map_parser::MemorySection]`
found type `&std::vec::Vec<&map_parser::MemorySection>`
我确实理解错误,但是我不知道要进行所需的转换。
如果仅使用“ parsed_result”调用该函数,则会出现此错误(应显示“ parsed_result”的类型)
error[E0308]: mismatched types
--> src\main.rs:24:38
|
24 | let mem_map = mem_planner::plan1(parsed_result);
| ^^^^^^^^^^^^^ expected reference, found struct `std::collections::HashMap`
|
= note: expected type `&[map_parser::MemorySection]`
found type `std::collections::HashMap<std::string::String, map_parser::MemorySection>`
最低工作示例:
mem_parser.rs
use std::collections::HashMap;
pub struct MemoryObject {
name: String,
size: usize,
}
pub struct MemorySection {
pub name: String,
pub size: usize,
pub objs: Vec<MemoryObject>,
}
pub type MemMap = HashMap<String, MemorySection>;
pub fn parse() -> MemMap {
let mut memory_sections = HashMap::new();
let section_name = "key".to_string();
let section_val = MemorySection {name: "readable name".to_string(), size: 10, objs: Vec::new() };
memory_sections.insert(section_name, section_val);
memory_sections
}
main.rs
mod mem_parser;
fn main() {
let parsed_result = mem_parser::parse();
let mut secs: Vec<_> = parsed_result.values().map(|ms| ms.clone()).collect();
let mem_map = plan1(&secs);
}
fn plan1(objects: &[mem_parser::MemorySection]) -> () {
println!("Test");
}