Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust 如何使BTreeMap::get返回字符串?_Rust - Fatal编程技术网

Rust 如何使BTreeMap::get返回字符串?

Rust 如何使BTreeMap::get返回字符串?,rust,Rust,函数的get()返回一个选项类型,该类型引用与键对应的值。因此,您在堆上存储了一个字符串,此函数根据键返回对该字符串的引用 我把你的例子缩短了一点。您有一个未初始化的BTreeMap,所以我首先初始化了它-让mut-map:BTreeMap=BTreeMap::new()。在您的情况下,您可以轻松地使用if let语句 src/main.rs:5:24: 5:39 error: mismatched types: expected `collections::string::String`,

函数的
get()
返回一个
选项
类型,该类型引用与键对应的值。因此,您在堆上存储了一个
字符串
,此函数根据键返回对该
字符串的引用

我把你的例子缩短了一点。您有一个未初始化的
BTreeMap
,所以我首先初始化了它-
让mut-map:BTreeMap=BTreeMap::new()。在您的情况下,您可以轻松地使用
if let
语句

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`.
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`.
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");
    }
}
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");
    }
}