打印向量的最后一个元素

Max*_*Max 1 rust

在 Rust 中,我发现我们可以使用.last()函数来访问向量的最后一个元素。但是,当我尝试将其插入到打印输出中时,如下所示

fn main() {
    let mut v: Vec<f64> = Vec::new();
    v.push(1.0); v.push(1.9); v.push(1.2);
    println!("Last element is {}", v.last());    // (*)
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误消息:

error[E0277]: `Option<&f64>` doesn't implement `std::fmt::Display`
Run Code Online (Sandbox Code Playgroud)

完整的错误文本提示我可以使用它{:?}。如果我更改(*)为 read println!("Last element is {:?}", v.last()); // (*),则程序会打印

Last element is Some(1.2)
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到Last element is 1.2

如何将值提取1.2f64

M.A*_*nin 7

可能有也可能没有最后一个元素,具体取决于 Vector 是否为空。

您可以检查Option<f64>返回的是否last()Some(val)if let这可以使用或match或其他技术(unwrap()等)来完成unwrap_or()。例如:

fn main() {
    let v = vec![1.0, 1.9, 1.2];
    if let Some(val) = v.last() { 
        println!("Last element is {}", val);
    } else {
        println!("The vector is empty");
    }
}
Run Code Online (Sandbox Code Playgroud)