{"id":2221,"date":"2022-02-17T21:43:27","date_gmt":"2022-02-18T03:43:27","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=2221"},"modified":"2022-04-25T09:32:46","modified_gmt":"2022-04-25T14:32:46","slug":"rust-find-index-of-element-in-array","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-find-index-of-element-in-array\/","title":{"rendered":"Rust | How to find the index of an element in an array?"},"content":{"rendered":"\n<p>No matter what programming language you use, finding the index of an element in an array is one of those common processes needed to perform different operations such as updating or removing an element of an array. Hopefully, this article not only gives you the solution but also a solid explanation of how to do it in Rust, especially for those who are new to this programming language.<\/p>\n\n\n\n<p><strong>To find the index of an element in an array in Rust, iterate through the elements of the array using the function <code>iter()<\/code>, followed by the <code>position()<\/code> function. Finally, use the <code>unwrap()<\/code> function to extract the contained value, which is the index of the array element.<\/strong> Let&#8217;s look at this implementation in code.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let my_array = &#91;\"a\", \"b\", \"c\"];\nlet index_element = my_array\n        .iter()\n        .position(|&amp;x| x == \"b\")\n        .unwrap();\n\nprint!(\"Index of b is {}\", index_element);<\/code><\/pre>\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-find-index-of-element-in-array\/#Understanding_the_solution\" >Understanding the solution<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-find-index-of-element-in-array\/#Solution_that_works_when_finding_the_index_of_an_element_in_slices_and_vectors\" >Solution that works when finding the index of an element in slices and vectors<\/a><\/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-find-index-of-element-in-array\/#Be_careful_using_unwrap_function\" >Be careful using unwrap() function<\/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-find-index-of-element-in-array\/#Using_into_iter_instead_of_iter_function\" >Using into_iter() instead of iter() function<\/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-find-index-of-element-in-array\/#Other_solution_to_find_index_of_an_element_of_an_array_Using_a_for_loop\" >Other solution to find index of an element of an array: Using a for loop<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-find-index-of-element-in-array\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\" id=\"understanding-the-solution\"><span class=\"ez-toc-section\" id=\"Understanding_the_solution\"><\/span>Understanding the solution<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>As previously stated, there are three functions used to find the index of an array element:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>iter()<\/li><li>position()<\/li><li>unwrap<\/li><\/ul>\n\n\n\n<p><strong>The <code>iter()<\/code> is a function that generates an Iterator trait which helps to iterate a collection of values by reference such as arrays, slices, vectors, etc<\/strong>. Therefore, the result from using <code>iter()<\/code> is an iterator of the type <code>T<\/code>, where <code>T<\/code> is the reference type of the elements of the array. In the previous example, the referemce types of the elements of the array <code>my_array<\/code> is <code>&amp;str<\/code>.<\/p>\n\n\n\n<p>Iterators have a wide range of functions available, among them is the <code>position()<\/code> function. <strong>The <code>position()<\/code> function searches for an element in an iterator, returning its index.<\/strong> This function uses a closure that executes against the elements in the iterator until it finds one element that meets the condition and returns true.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let my_array = &#91;\"a\", \"b\", \"c\"];\nlet index_element = my_array\n        .iter()\n        .position(|&amp;x| x == \"b\");\n\n\/\/ in other words, it will run the closure for each \n\/\/ element of my_array, .i.e.,\n\/\/ if (\"a\" == \"b\") return true; This will return false, get the next element\n\/\/ if (\"b\" == \"b\") return true; This will return true, stop processing other elements\n\/\/ if (\"c\" == \"b\") return true; This won't reach to element \"c\" as it has previously found an element that meets the condition defined in the closure<\/code><\/pre>\n\n\n\n<p>The closure passed in the <code>position()<\/code> doesn&#8217;t necessarily get executed on each element of the array as it will stop processing other elements as soon as it finds one element that meets the condition defined in the closure returning as a result <code>true<\/code>.<\/p>\n\n\n\n<p>The <code>position()<\/code> function returns a value of type <code>Option&lt;usize&gt;<\/code>. This type contains the value of the index of the element in the array, but is not necessarily a numeric type <code>&lt;usize&gt;<\/code>. Instead, the value could be <code>Some(index)<\/code>. Hence, <strong>to extract the value of the type <code>Option<\/code>, use the <code>unwrap()<\/code> function<\/strong>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let my_array = &#91;\"a\", \"b\", \"c\"];\nlet option_index_element = my_array\n        .iter()\n        .position(|&amp;x| x == \"b\"); \n\/\/ At this point, option_index_element = Some(1)\n\nlet index_element = option_index_element.unwrap();\n\/\/ index_element = 1;<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"solution-that-works-when-finding-the-index-of-an-element-in-slices-and-vectors\"><span class=\"ez-toc-section\" id=\"Solution_that_works_when_finding_the_index_of_an_element_in_slices_and_vectors\"><\/span>Solution that works when finding the index of an element in slices and vectors<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>This solution works in case you want to find the index of an element in a slice or a vector. As a quick reminder,<strong> a vector is a growable array<\/strong>, and <strong>a slice is a sequence of elements in a collection<\/strong>.<\/p>\n\n\n\n<p>Below, you should find two examples of finding the index of <code>\"b\"<\/code> in a vector and in a slice. <\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let my_vector = vec!&#91;\"a\", \"b\", \"c\"];\nlet vector_index_element = my_vector\n   .iter()\n   .position(|&amp;x| x == \"b\")\n   .unwrap();\nprintln!(\"Index of b is {} in vector\", vector_index_element);\n\nlet my_string = String::from(\"abcdefg\");\nlet my_slice = my_string.as_bytes();\nlet slice_index_element = my_slice\n   .iter()\n   .position(|&amp;x| x == \"b\".as_bytes()&#91;0])\n   .unwrap();\nprintln!(\"Index of b is {} in slice\", slice_index_element);<\/code><\/pre>\n\n\n\n<p>Notice how it is practically the same implementation on a vector. However, when working with a slice of a string, we converted the string character to bytes and modified the closure definition used in the <code>position()<\/code> function.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"be-careful-using-unwrap-function\"><span class=\"ez-toc-section\" id=\"Be_careful_using_unwrap_function\"><\/span>Be careful using <code>unwrap()<\/code> function<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>There can be a scenario where you could be trying to find the index of an element that doesn&#8217;t exist in an array. In our example, it could be trying to search for the index of <code>\"d\"<\/code> where the array only has the values <code>[\"a\", \"b\", \"c\"]<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let my_array = &#91;\"a\", \"b\", \"c\"];\nlet index_element = my_array\n   .iter()\n   .position(|&amp;x| x == \"d\")\n   .unwrap(); \/\/ &lt;- program panics in here<\/code><\/pre>\n\n\n\n<p><strong>The <code>position()<\/code> function returns an <code>Option&lt;usize&gt;<\/code>, which can be either <code>Some(index)<\/code> whenever the value exists, or <code>None<\/code> whenever the value doesn&#8217;t exist.<\/strong><\/p>\n\n\n\n<p>The problem happens when using the <code>unwrap()<\/code> function. <strong><a href=\"https:\/\/doc.rust-lang.org\/std\/option\/enum.Option.html#panics-1\" target=\"_blank\" rel=\"noopener\">The <code>unwrap()<\/code> function panics if the value that is trying to extract equals None<\/a><\/strong>. Whenever this happens, your code will fail.<\/p>\n\n\n\n<p>Luckily, there are other alternatives besides using <code>unwrap()<\/code> in case you are unsure if the element you are searching for the index is part of the array: <code>unwrap_or()<\/code> or <code>unwrap_or_else()<\/code>. Both <code>unwrap_or()<\/code> and <code>unwrap_or_else()<\/code> return a default value in case the value is <code>None<\/code>.<\/p>\n\n\n\n<p>To use <code>unwrap_or()<\/code> function, provide a default value as a parameter.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let index_element = my_array\n   .iter()\n   .position(|&amp;x| x == \"d\")\n   .unwrap_or(0);\n\/\/ index_element = 0<\/code><\/pre>\n\n\n\n<p>To use <code>unwrap_or_else()<\/code>, provide a closure returning a default value as a parameter.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let index_element = my_array\n   .iter()\n   .position(|&amp;x| x == \"d\")\n   .unwrap_or_else(|| 0);\n\/\/ index_element = 0<\/code><\/pre>\n\n\n\n<p><strong>Note:<\/strong> By using <code>unwrap_or()<\/code> or <code>unwrap_or_else()<\/code> we could run into another problem: to automatically default to using an index of a non-related element. In the end, it all comes down to what logic fit best your project.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"using-into-iter-instead-of-iter-function\"><span class=\"ez-toc-section\" id=\"Using_into_iter_instead_of_iter_function\"><\/span>Using <code>into_iter()<\/code> instead of <code>iter()<\/code> function<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Similar to using <code>iter()<\/code> function, there is another function called <code>into_iter()<\/code> which you can use to find the index of an element in an array.<\/p>\n\n\n\n<p>On one hand, <strong>the <code>iter()<\/code> function creates an iterator in which the values are passed by reference<\/strong>. Hence, that is why it is necessary to use <code>&amp;<\/code> or borrow expression to access the value of the reference.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let index_element = my_array\n   .iter()\n   .position(|&amp;x| x == \"d\") \/\/ &amp;x -&gt; accessing the element value by reference\n   .unwrap();<\/code><\/pre>\n\n\n\n<p><strong>The <code>into_iter()<\/code> function creates an iterator by value<\/strong>. This means it is no longer necessary to use <code>&amp;<\/code> or borrow expression to access the value as the iterator already has the value of the collection, in our case, the array.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let my_array = &#91;\"a\", \"b\", \"c\"];\nlet option_index_element = my_array\n        .into_iter()\n        .position(|x| x == \"b\") \/\/ x -&gt; accessing the element value directly\n        .unwrap();<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"other-solution-to-find-index-of-an-element-of-an-array-using-a-for-loop\"><span class=\"ez-toc-section\" id=\"Other_solution_to_find_index_of_an_element_of_an_array_Using_a_for_loop\"><\/span>Other solution to find index of an element of an array: Using a <code>for<\/code> loop<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Besides the solution presented above, it is possible to find the index of an array using a traditional <code>for<\/code> loop by iterating the array using <code>enumerate()<\/code> function found on Iterators, or whenever <code>iter()<\/code> function is used in an array.<\/p>\n\n\n\n<p><strong>The <code>enumerate()<\/code> function returns an iterator with a pair of <code>i<\/code> and <code>val<\/code> , where <code>i<\/code> is the current index and <code>val<\/code> is the current value.<\/strong> <\/p>\n\n\n\n<p><strong>Note:<\/strong> You can assign any variable name to the pair <code>(i, val)<\/code>. For instance, in the following snippet of code, <code>x<\/code> represents <code>val<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let mut index = None;\nfor (i, x) in array.iter().enumerate() {\n    if x.to_string() == \"b\" {\n        index = Some(i);\n        break;\n    }\n}\n\nprintln!(\"index {}\", index.unwrap());<\/code><\/pre>\n\n\n\n<p><strong>Note<\/strong>: Initially, you might think the solution of using the <code>position()<\/code> function is better. However, it all comes down to what logic the program needs to run.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"conclusion\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>All in all, this article showed you different ways to find the index of an element of an array by using some type of iterator trait, either <code>Iterator<\/code> or <code>IntoIterator<\/code> traits to then access functions such as <code>position()<\/code> or <code>enumerate()<\/code> in order to define conditional statements to identify the correct element of the array.<\/p>\n\n\n\n<p><strong>Was this article helpful?<\/strong><\/p>\n\n\n\n<p><strong>I hope this tutorial helped you to clarify doubts and concepts of Rust, especially to those new to the programming language<\/strong>.<\/p>\n\n\n\n<p>Share your thoughts by replying on Twitter of <a href=\"https:\/\/twitter.com\/bbprogrammer\" target=\"_blank\" rel=\"noreferrer noopener\">Become A Better Programmer<\/a> or to <a href=\"https:\/\/twitter.com\/arealesramirez\" target=\"_blank\" rel=\"noreferrer noopener\">personal my Twitter account<\/a>.<\/p>\n\n\n\n<figure class=\"wp-block-embed aligncenter is-type-rich is-provider-twitter wp-block-embed-twitter\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"twitter-tweet\" data-width=\"550\" data-dnt=\"true\"><p lang=\"en\" dir=\"ltr\">Who would have thought you could learn so much in <a href=\"https:\/\/twitter.com\/hashtag\/rustlang?src=hash&amp;ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">#rustlang<\/a> by finding the element of an array?<br><br>This task sounds easy&#8230; but is it?<br><br>The solution has plenty of concepts that might not be that easy when <a href=\"https:\/\/twitter.com\/hashtag\/learning?src=hash&amp;ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">#learning<\/a> this <a href=\"https:\/\/twitter.com\/hashtag\/programming?src=hash&amp;ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">#programming<\/a> language.<a href=\"https:\/\/t.co\/R2HSLhNUkr\">https:\/\/t.co\/R2HSLhNUkr<\/a><\/p>&mdash; Become A Better Programmer (@bbprogrammer) <a href=\"https:\/\/twitter.com\/bbprogrammer\/status\/1494519468445290524?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">February 18, 2022<\/a><\/blockquote><script async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script>\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>Finding the index of an element in an array is a common process used in any programming language. Learn how to do it in Rust with a comprehensive explanation<\/p>\n","protected":false},"author":1,"featured_media":2227,"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-2221","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\/2221","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=2221"}],"version-history":[{"count":4,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2221\/revisions"}],"predecessor-version":[{"id":2453,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2221\/revisions\/2453"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/2227"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=2221"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=2221"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=2221"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}