0

I have such 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);
    }
}

What I'm trying to do is to pass each book value into a related function (I know it probably could be done some dumber or smarter way, yet I need to use related function). The problem is I'm getting this error:

expected struct models::NewBook, found reference

If I do Book::print_title(*book); then I get

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

So the question is how can I pass the value of a book to the related function print_title? books array won't be ever reused and I won't ever need book values if that matters.

eawer
  • 1,398
  • 3
  • 13
  • 25
  • 1
    When it comes to `into_iter`, array is kinda special, see duplicate for the gory detail. You can either make function `print_title` taking a reference or define `books` as a `Vec` like so: `let books = vec![...]`. – edwardw Dec 12 '19 at 15:23
  • `for` calls `into_iter` implicitly, just FYI. `for X in Y.into_iter()` is virtually always a mistake. It may compile, but has different semantics than plain `for X in Y` which is normally what you mean. – trent Dec 12 '19 at 18:38
  • @trentcl if I remove `into_iter` I receive ```borrow the array with `&` or call `.iter()` on it to iterate over it``` while with `into_iter` it works as expected – eawer Dec 17 '19 at 12:11
  • *it works as expected*? Obviously, it doesn't, because you meant to iterate over `books` by value and you got it by reference. If you really wanted to iterate over `books` by reference, you could have followed the compiler's advice: `for book in &books` does the same thing (and causes the same error). Again: `for book in books.into_iter()` is *virtually always* a mistake. – trent Dec 17 '19 at 12:41

0 Answers0