use std::collections::btree_map::BTreeMap;
fn main() {
let mut map: BTreeMap<String, String>;
map.insert("name".to_string(), "aho".to_string());
let name: String = map.get("name");
println!("welcom, {}", name);
}
cargo build
:
src/main.rs:5:24: 5:39 error: mismatched types:
expected `collections::string::String`,
found `core::option::Option<&collections::string::String>`
(expected struct `collections::string::String`,
found enum `core::option::Option`) [E0308]
src/main.rs:5 let name: String = map.get("name");
^~~~~~~~~~~~~~~
src/main.rs:5:24: 5:39 help: run `rustc --explain E0308` to see a detailed explanation
error: aborting due to previous error
Could not compile `hello_world`.
The get()
function returns an Option
type with a reference to the value corresponding to the key. So you have stored a String
on the heap and this function returns a reference to that String
based on the key.
I made your example a little shorter. You had an uninitialized BTreeMap
, so I initialized it first - let mut map: BTreeMap<String, String> = BTreeMap::new();
. In your case you can easily use an if let
statement.
use std::collections::BTreeMap;
fn main() {
let mut map: BTreeMap<String, String> = BTreeMap::new();
map.insert("name".into(), "aho".into());
if let Some(name) = map.get("name") {
println!("welcome, {}", name);
} else {
println!("welcome, stranger");
}
}
But if you really want to return a String
value, you must first extract the Some(name)
part of the Option
type and then clone it using a clone()
function. Because BTreeMap
owns this String
value, you can't move it out without cloning it. clone()
makes a copy of the original value.
use std::collections::BTreeMap;
fn main() {
let mut map: BTreeMap<String, String> = BTreeMap::new();
map.insert("name".into(), "aho".into());
if let Some(name) = map.get("name") {
let name: String = name.clone();
println!("welcome, {}", name);
} else {
println!("welcome, stranger");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.