{"id":2896,"date":"2022-07-10T09:39:17","date_gmt":"2022-07-10T14:39:17","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=2896"},"modified":"2022-07-10T09:39:21","modified_gmt":"2022-07-10T14:39:21","slug":"rust-iter-vs-iter_mut-vs-into_iter","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-iter-vs-iter_mut-vs-into_iter\/","title":{"rendered":"Rust | Difference Between iter(), iter_mut(), into_iter()"},"content":{"rendered":"\n<p>Rust iterators are data structures that contain a sequence of objects and allow the programmer to <em>iterate<\/em> them efficiently. However, like most things in Rust, iterators have a steep learning curve. The primary functions and concepts can be daunting, but don\u2019t worry, we are here to do our absolute best to explain them.<\/p>\n\n\n\n<p><strong>All three methods <code>iter()<\/code>, <code>into_iter()<\/code> and <code>iter_mut()<\/code> ultimately iterate the iterator. They differ by the handle of each iterated object <em>T<\/em>:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong><code>iter()<\/code> yields <code>&amp;T<\/code><em> <\/em><\/strong>&#8211; <strong>immutable references.<\/strong><\/li><li><strong><code>iter_mut()<\/code> yields, as the name suggests, <code>&amp;mut T<\/code><em> <\/em>&#8211; mutable references.<\/strong><\/li><li><strong><code>into_iter()<\/code> yields any of T (moved value), <code>&amp;T<\/code> or <code>&amp;mut T<\/code> depending on the usage.<\/strong><\/li><\/ul>\n\n\n\n<p>If the differences between iter(), into_iter(), and iter_mut() are not still clear, keep reading this post. You will learn more about each of these methods, helping you understand them by looking at easy-to-follow examples.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-iter-vs-iter_mut-vs-into_iter\/#Understanding_iter_and_Basic_Iterator_Functionality\" >Understanding iter()  and Basic Iterator Functionality<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-iter-vs-iter_mut-vs-into_iter\/#Lazy_Evaluation_and_Consuming_Iterators\" >Lazy Evaluation and Consuming Iterators<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-iter-vs-iter_mut-vs-into_iter\/#Understanding_iter_mut\" >Understanding iter_mut()<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-iter-vs-iter_mut-vs-into_iter\/#Understanding_into_iter\" >Understanding into_iter()<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-iter-vs-iter_mut-vs-into_iter\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Understanding_iter_and_Basic_Iterator_Functionality\"><\/span><a id=\"post-2896-_fctcdhc2a4hl\"><\/a>Understanding <strong><code>iter() <\/code><\/strong> and Basic Iterator Functionality<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><strong><code><a href=\"https:\/\/doc.rust-lang.org\/stable\/std\/iter\/\" target=\"_blank\" rel=\"noopener\">iter()<\/a><\/code><\/strong> is the most common method out of the three, and most examples online use it. It allows the programmer to iterate each value as an immutable reference. Let us look at a small example:<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let fruits = vec!&#91;\"Banana\", \"Apple\", \"Grapes\", \"Pineapple\"];\r\n    println!(\r\n        \"{}\",\r\n        fruits\r\n            .iter()\r\n            .map(|fruit_name: &amp;&amp;str| fruit_name.len())\r\n            .fold(0, |accumulated, fruit_name_length| {\r\n                accumulated + fruit_name_length\r\n            })\r\n    ); \/\/ Should print 26<\/code><\/pre>\n\n\n\n<p>This example demonstrates a couple of things; let us go over it one line at a time.<\/p>\n\n\n\n<p>The first line defines a new variable named <strong><code>fruits<\/code><\/strong>  and assigns to it a vector (<strong><code>Vec&lt;&amp;str><\/code><\/strong>) of four fruit names using the <strong><code>vec!<\/code><\/strong> Macro.<\/p>\n\n\n\n<p>The second and third lines order Rust to print the output of the statement that starts in the fourth line.<\/p>\n\n\n\n<p>Here (line 5) we see the call to the <strong><code>iter()<\/code><\/strong> method, which allows us to call the first actual iterator method &#8211; <strong><code>map<\/code><\/strong>. <a href=\"https:\/\/doc.rust-lang.org\/stable\/std\/iter\/struct.Map.html\" target=\"_blank\" rel=\"noopener\"><strong><code>map<\/code><\/strong> <\/a>is one of many methods that is called on an iterator and returns a new iterator.<\/p>\n\n\n\n<p>The name \u201c<em>map\u201d<\/em> is not specific to Rust and is used in many other programming languages for a function that <em>maps <\/em>each element in a sequence of elements to another element (most commonly creates a modified version of the original element) in a new sequence.<\/p>\n\n\n\n<p>In this simple example, I use the <strong><code>map<\/code><em> <\/em><\/strong>method to <em>map<\/em> each <strong><code>fruit_name<\/code><\/strong> element in the <strong><code>fruits<\/code><\/strong> vector to its length. Notice the parameter that <strong><code>map<\/code><\/strong> receives &#8211; that is called a <em>closure<\/em>. A closure is an anonymous function (a function with no name) that can be stored in a variable or passed as an argument to another function.<\/p>\n\n\n\n<p>I passed a closure to <strong><code>map<\/code><\/strong> that receives as a parameter (between the <strong><em>| <\/em><\/strong>characters) a <strong><code>fruit_name<\/code><\/strong> of type <strong><code>&amp;&amp;str<\/code><\/strong>. The type <strong><code>&amp;&amp;str<\/code><\/strong> is expected; we are iterating <strong><code>&amp;str<\/code><\/strong> elements using <strong><code>iter()<\/code><\/strong> which yields immutable references to the elements in the iterator. The closure returns the length of <strong><code>fruit_name<\/code><\/strong>.<\/p>\n\n\n\n<p>The next call is to the<strong><em> <\/em><code><a href=\"https:\/\/doc.rust-lang.org\/stable\/std\/iter\/trait.Iterator.html#method.fold\" target=\"_blank\" rel=\"noopener\">fold<\/a><\/code><\/strong> method, which iterates the entire iterator and calculates a cumulating single value. The <strong><code>fold<\/code><\/strong> method receives two parameters:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>The initial accumulated value (the starting value; the value built upon).<\/li><li>A closure that executes for each element in the iterator and receives two parameters:\n<ol>\n<li>The accumulated value so far.<\/li>\n<li>The current element.<\/li>\n<\/ol>\n<\/li><\/ol>\n\n\n\n<p>In this example, the sum of all fruit lengths is calculated, with an initial value of 0. In this case, it would also make sense to use the <strong><code><a href=\"https:\/\/doc.rust-lang.org\/stable\/std\/iter\/trait.Iterator.html#method.reduce\" target=\"_blank\" rel=\"noopener\">reduce<\/a><\/code><\/strong> method that uses the first element of the iterator instead of taking the initial accumulated value as a parameter.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Lazy_Evaluation_and_Consuming_Iterators\"><\/span><a id=\"post-2896-_onk98kz7jnfu\"><\/a>Lazy Evaluation and Consuming Iterators<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The call to the <strong><code>fold<\/code><\/strong> method is special since it <em>consumes<\/em> the entire iterator. To understand what <em>consuming <\/em>means, we first must understand that Rust iterators are lazily evaluated, meaning no actual calculation is performed until the result is requested. A classic example of this mechanism is the <strong><code><a href=\"https:\/\/doc.rust-lang.org\/stable\/std\/iter\/trait.Iterator.html#tymethod.next\" target=\"_blank\" rel=\"noopener\">next<\/a><\/code><\/strong> method. Let\u2019s look at how it is used:<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>println!(\r\n        \"{}\",\r\n        fruits\r\n            .iter()\r\n            .next()\r\n            .unwrap()\r\n    ); \/\/ Should print \u201cBanana\u201d<\/code><\/pre>\n\n\n\n<p>The <strong><code>next<\/code><\/strong> method consumes the <em>first <\/em>element of the iterator, meaning it triggers its calculation and removes it from the iterator. It is important to note that <strong><code>next<\/code><\/strong> returns an <strong><code>Option<\/code><em> <\/em><\/strong>(more about the <strong><code>Option<\/code><\/strong> enum <a href=\"https:\/\/doc.rust-lang.org\/std\/option\/\" target=\"_blank\" rel=\"noopener\">here<\/a>), which might contain <strong><code>None<\/code><\/strong> if <strong><code>next<\/code><\/strong> is called on an empty iterator.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Understanding_iter_mut\"><\/span><a id=\"post-2896-_xuesar4mf5q0\"><\/a>Understanding iter_mut()<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><strong><code><a href=\"https:\/\/doc.rust-lang.org\/stable\/std\/primitive.slice.html#method.iter_mut\" target=\"_blank\" rel=\"noopener\">iter_mut()<\/a><\/code><em> <\/em><\/strong>is the least used method out of the three. It allows the programmer to iterate each element as a mutable reference. Let us look at a small example:<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let mut numbers = vec!&#91;1, 2, 3, 4];\nnumbers.iter_mut().for_each(|n| *n += 1);\nprintln!(\"{:?}\", numbers); \/\/ Should print &#91;2, 3, 4, 5]<\/code><\/pre>\n\n\n\n<p>In this example, we define a mutable vector of numbers and iterate it using <strong><code>iter_mut()<\/code><\/strong>. The second line also introduces a new method: <strong><code>for_each()<\/code><\/strong>. <strong><code>for_each()<\/code><\/strong> is the one-line version of iterating using the <strong><code>for<\/code><\/strong> keyword like so:<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>for n in numbers.iter_mut() {\n        *n += 1;\n}<\/code><\/pre>\n\n\n\n<p><strong><code>for_each()<\/code><\/strong> receives a parameter which is a closure to execute the <em>for each<\/em> element in the iterator. Since we are using <strong><code>iter_mut<\/code><\/strong>, we are iterating mutable references, which means the closure can modify every number <strong><code>n<\/code><\/strong> in the original vector using dereferencing<em>.<\/em><\/p>\n\n\n\n<p>It is important to note that since iterators are lazy, using methods like <strong><code>map<\/code><\/strong>, <strong><code>fold<\/code><em>,<\/em><\/strong> and <strong><code>reduce<\/code><\/strong> without consuming the iterators won\u2019t change the elements of the vector.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Understanding_into_iter\"><\/span><a id=\"post-2896-_8cjzcgrzj8jk\"><\/a>Understanding into_iter()<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><strong><code>into_iter()<\/code><\/strong> is a method whose name comes from the trait <strong><code>IntoIterator<\/code><\/strong> which we must understand before we continue. <strong><code>IntoIterator<\/code><em> <\/em><\/strong>is a trait that should be implemented when the developer wants to specify how a certain type should be converted <em>into an iterator<\/em>. It is useful when the type represents some sort of collection of data and most notably allows for an iteration over objects of the type in a <strong><em>for<\/em><\/strong> loop syntax.<\/p>\n\n\n\n<p>Let\u2019s look at an example before we continue to <strong><code>into_iter()<\/code><\/strong>.<\/p>\n\n\n\n<p>The type <strong><code>Vec&lt;T><\/code><\/strong> implements <strong><code>IntoIterator<\/code><\/strong> for three cases:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong><code>impl&lt;T> IntoIterator for Vec&lt;T><\/code> <\/strong><\/li><li><strong><code>impl&lt;'a, T> IntoIterator for &amp;'a Vec&lt;T><\/code><\/strong><\/li><li><strong><code>impl&lt;'a, T> IntoIterator for &amp;'a mut Vec&lt;T><\/code><\/strong><\/li><\/ul>\n\n\n\n<p>The first implementation allows for iterating by value (yields <strong><code>T<\/code><\/strong>s), it implements <strong><code>IntoIterator<\/code><\/strong> for a <strong><code>Vec<\/code><\/strong> that holds elements of some generic type <strong><code>T<\/code><\/strong>.<\/p>\n\n\n\n<p>The second implementation allows for iterating by reference (yields <strong><code>&amp;T<\/code><\/strong>s), it implements <strong><code>IntoIterator<\/code><\/strong> for a reference of generic lifetime <strong><code>\u2018a<\/code><\/strong> to a <strong><code>Vec<\/code> <\/strong>that holds elements of some generic type <strong><code>T<\/code><\/strong>.<\/p>\n\n\n\n<p>The third implementation is similar to the second implementation, but with a generic mutable reference instead.<\/p>\n\n\n\n<p>Those three implementations allow the following code snippet to compile:<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let by_value = vec!&#91;1, 2, 3];\r\n    for i in by_value {\r\n        println!(\"{}\", i);\r\n    }\r\n    \/\/ println!(\"{:?}\", by_value);\r\n\r\n    let by_reference = vec!&#91;1, 2, 3];\r\n\r\n    for i in &amp;by_reference {\r\n        println!(\"{}\", i);\r\n    }\r\n\r\n    println!(\"{:?}\", by_reference);\r\n\r\n    let mut by_mutable_reference = vec!&#91;1, 2, 3];\r\n    for i in &amp;mut by_mutable_reference {\r\n        *i += 1;\r\n    }\r\n    println!(\"{:?}\", by_mutable_reference);<\/code><\/pre>\n\n\n\n<p>This snippet is long so I\u2019ll explain it in multiple parts.<\/p>\n\n\n\n<p>In the first part (lines 1 to 5), we iterate the <strong><code>by_value<\/code> <\/strong>vector <em>by value<\/em> and print its elements. It is important to note that since we are iterating the elements <em>by value,<\/em> the elements are moved and so it is impossible to print its elements after the <strong><code>for<\/code><em> <\/em><\/strong>loop.<\/p>\n\n\n\n<p>In the second part (lines 7 to 13), we iterate the <strong><code>by_reference<\/code><\/strong> vector <em>by reference <\/em>and print its elements. Now, since we are iterating the elements <em>by reference,<\/em> the elements are <em>not<\/em> moved and so printing the elements again after the <strong><code>for<\/code><em> <\/em><\/strong>loop is indeed possible.<\/p>\n\n\n\n<p>In the third and last part (lines 15 to 19), we iterate the <strong><code>by_mutable_reference<\/code><\/strong> vector <em>by mutable reference<\/em>, add 1 to every one of its elements and then we can print the vector as expected.<\/p>\n\n\n\n<p>In all three cases, <strong><code>into_iter<\/code><\/strong> is called <em>implicitly <\/em>and in all three cases, the elements are handled differently &#8211; <strong><code>i32<\/code><\/strong>, <strong><code>&amp;i32<\/code><em>,<\/em><\/strong> and <strong><code>&amp;mut i32<\/code><em> <\/em><\/strong>(in order).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span><a id=\"post-2896-_tmes0pf4u3pg\"><\/a>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In conclusion, <strong><code>iter()<\/code><\/strong>, <strong><code>iter_mut()<\/code><\/strong> and <strong><code>into_iter()<\/code><em> <\/em><\/strong>are ultimately methods that allow the programmer to <em>iterate <\/em>over a collection of data.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong><code>iter()<\/code><\/strong> provides iteration over immutable references (<strong><code>&amp;T<\/code><\/strong>).<\/li><li><strong><code>iter_mut()<\/code><\/strong> provides iteration over mutable references (<strong><code>&amp;mut T<\/code><\/strong>).<\/li><li><strong><code>into_iter()<\/code><\/strong> allows for iteration over any of the moved values (<strong><code>T<\/code><\/strong>), immutable references, or mutable references. In addition, it is also implicitly called (when possible) when using a <strong><code>for<\/code><\/strong> loop to iterate the collection.<\/li><\/ul>\n\n\n\n<p><strong>Was this article helpful?<\/strong><\/p>\n\n\n\n<p>Share your thoughts by replying on <a href=\"https:\/\/twitter.com\/bbprogrammer\" target=\"_blank\" rel=\"noopener\">Twitter of Become A Better Programmer<\/a> or to my <a href=\"https:\/\/twitter.com\/arealesramirez\" target=\"_blank\" rel=\"noopener\">personal Twitter account<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Rust iterators are data structures that contain a sequence of objects and allow the programmer to iterate them efficiently. However, like most things in Rust, iterators have a steep learning curve. The primary functions and concepts can be daunting, but don\u2019t worry, we are here to do our absolute best to explain them. All three &#8230; <a title=\"Rust | Difference Between iter(), iter_mut(), into_iter()\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-iter-vs-iter_mut-vs-into_iter\/\" aria-label=\"More on Rust | Difference Between iter(), iter_mut(), into_iter()\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":2898,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[31],"tags":[],"class_list":["post-2896","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-rust","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2896","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=2896"}],"version-history":[{"count":2,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2896\/revisions"}],"predecessor-version":[{"id":2899,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2896\/revisions\/2899"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/2898"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=2896"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=2896"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=2896"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}