News for hackers. Stuff that matters.
Re:Rust Ownership Explained with Python by atoav on Sunday September 30, 2018 @06:46AM (#18105607)
Because it runs on an iterator. And anything that runs on an iterator consumes it. If you for example run

    // Make a iterator
    let test_iterator = vec![1, 2, 3].into_iter();
    
    // count() iterates over the elements and consumes them
    let count = test_iterator.count();
    
    // because the values have been consumed, this is not possible
    for element in test_iterator{
        println!("{}", element);
    }
See: https://play.rust-lang.org/?gist=750dffd641ac237690defbf86da...

The count method will consume every element, and return the length. This is because iterators are meant to be consumed when iterated. This is maybe inconvenient, but necessary because of the generic nature of the iterator trait: for some things that implement the iterator trait it is just not possible to get the max(), min() or count without consuming the iterator. So this would work:

    // Make a iterator
    let test = vec![1, 2, 3];
    
    // Create an Iterator and consume it with count()
    let count = test.iter().count();
    println!("Count: {}\n", count);
    
    // Create another Iterator and loop over it (consume it in each row)
    for element in test.iter(){
        println!("{}", element);
    }
    
    // Create another Iterator and consume it with min()
    let min = test.iter().min();
    println!("\nMin: {}", min.unwrap());
Try here: https://play.rust-lang.org/?gist=498ffd9afa163909745d8537e97...

That means, there was probably the choice: try keeping it generic and consistent for all things that implement iterator or making these methods something that works fine with basic types but not at all with anything more complex.

So: Iterators don't know any value until they are consumed. That means iterators will be consumed most of the time (there are exceptions.

Also see: https://doc.rust-lang.org/std/iter/index.html#implementing-i... And: https://doc.rust-lang.org/std/iter/trait.Iterator.html

There are no comments on this comment yet.