arrays - 在 Rust 中将数组值推送到向量

标签 arrays vector rust

Rust 编程语言有一个任务要打印 The Twelve Days of Christmas利用其重复性。

我的想法是将所有礼物收集在一个数组中,并将它们推送到向量中,该向量将在迭代之间打印。

看来这要么不可能,要么不容易,要么我什么也没得到。

代码:

fn main() {
    let presents = [
        "A song and a Christmas tree",
        "Two candy canes",
        "Three boughs of holly",
    ];

    let mut current_presents = Vec::new();

    for day in presents {
        current_presents.push(presents[day]);
        println!(
            "On the {} day of Christmas my good friends brought to me",
            day + 1
        );
        println!("{current_presents} /n");
    }
}
error[E0277]: the type `[&str]` cannot be indexed by `&str`
  --> src/main.rs:11:31
   |
11 |         current_presents.push(presents[day]);
   |                               ^^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
   |
   = help: the trait `SliceIndex<[&str]>` is not implemented for `&str`
   = note: required because of the requirements on the impl of `Index<&str>` for `[&str]`

error[E0369]: cannot add `{integer}` to `&str`
  --> src/main.rs:14:17
   |
14 |             day + 1
   |             --- ^ - {integer}
   |             |
   |             &str

error[E0277]: `Vec<_>` doesn't implement `std::fmt::Display`
  --> src/main.rs:16:20
   |
16 |         println!("{current_presents} /n");
   |                    ^^^^^^^^^^^^^^^^ `Vec<_>` cannot be formatted with the default formatter
   |
   = help: the trait `std::fmt::Display` is not implemented for `Vec<_>`
   = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
   = note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info)

请帮助我调试或插入我走向正确的方向,而不是键入 12 个单独的字符串并将它们一一打印。

最佳答案

这有效:

fn main() {
    let presents = [
        "A song and a Christmas tree",
        "Two candy canes",
        "Three boughs of holly",
    ];

    let mut current_presents = Vec::new();

    for (day, present) in presents.iter().enumerate() {
        current_presents.push(present);
        println!(
            "On the {} day of Christmas my good friends brought to me",
            day + 1
        );
        println!("{current_presents:?}\n");
    }
}

关于arrays - 在 Rust 中将数组值推送到向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72163796/

相关文章:

c++ - Visual C++ 2012 在类中使用 std::vector 或 std::list

C++ 在编译时将图像像素嵌入 vector 内?

Objective-C 原始数组

python - 我只需要附加那些在 pyspark 数据框中具有非空值的人

r - 保留该列表(在 R 中)内没有适当子集的元素(来自向量列表)

rust - 在给定父模块上下文中的路径的子模块上下文中生成路径

Rust:将值移出选项并压入堆栈

utf-8 - 使用rust 的println!在某些情况下打印奇怪的字符

java - 字母数字拨号盘搜索 - Java/Android

javascript - 排序数组和 indexOf() 运行时