在遍历结构数组的同时访问结构的值

时间:2019-12-12 15:11:53

标签: rust

我有这样的code

fn main() {
    pub struct Book {
        pub title: String,
        pub author: String,
    };

    impl Book {
        fn print_title(book: Book) {
            println!("{}", book.title);
        }
    }

    let books: [Book; 2] = [
        Book {
            title: String::from("Best Served Cold"),
            author: String::from("Joe Abercrombie"),
        },
        Book {
            title: String::from("The Lord of the Rings"),
            author: String::from("John Tolkien"),
        },
    ];
    for book in books.into_iter() {
        Book::print_title(book);
    }
}

我想做的是将每个book值传递给一个相关的函数(我知道它可能以某种愚蠢或更聪明的方式完成,但是我需要使用相关的函数)。问题是我遇到此错误:

expected struct models::NewBook, found reference

如果我做Book::print_title(*book);,那么我会得到

cannot move out of `*book` which is behind a shared reference

所以问题是如何将book传递给相关函数print_titlebooks数组将永远不会被重用,如果那很重要,我将永远不需要book值。

0 个答案:

没有答案