我正在完成 Rust 书第 8 章中的练习。但是这个问题并不是特定于该练习的。它特定于此行:*entry.push(name)。我试图取消引用条目以使向量推入我的值,但出现此错误:
error[E0614]: type `()` cannot be dereferenced
--> src/main.rs:36:17
|
36 | *entry.push(name)
| ^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
根据 VSCode 的 Rust 分析器, 的类型entry是&mut Vec<&&str>. 我怀疑&&可能不是一个原因&导致了这个问题。但我不知道为什么 VSCode 会这么想。谁能告诉我我在这里做错了什么?
这是完整的代码:
use std::{io::{self}, collections::HashMap};
fn main() {
let mut store = HashMap::new();
loop {
println!("Enter a command:");
let mut command = String::new();
io::stdin()
.read_line(&mut command)
.expect("Failed to read command");
let split_command: Vec<&str> = command.split_whitespace().collect();
match split_command.as_slice() {
["Add", name, "to", department] => {
let entry = store.entry(department).or_insert(Vec::new());
*entry.push(name)
},
["Exit"] => {
break;
},
["Show", ..] => {
},
[_, ..] => {
},
[] => {
println!("No command!")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
谁能告诉我我在这里做错了什么?
您试图取消引用entry,这是完全不必要的,因为方法调用无论如何都会自动取消引用。
此外,*Rust 中的绑定能力相当低,所以你写的解析为
*(entry.push(name))
Run Code Online (Sandbox Code Playgroud)
因此,您尝试取消引用 的结果Vec::push,即(),它不是指针,因此不能取消引用,这正是编译器告诉您的:
类型
()无法取消引用
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |