<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: wrongbyte</title>
    <description>The latest articles on DEV Community by wrongbyte (@wrongbyte).</description>
    <link>https://dev.to/wrongbyte</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F800212%2Fbaa42db6-3089-4e0c-8bbb-3bab71f4b318.jpg</url>
      <title>DEV Community: wrongbyte</title>
      <link>https://dev.to/wrongbyte</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/wrongbyte"/>
    <language>en</language>
    <item>
      <title>Introduction to graphs - BFS algorithm</title>
      <dc:creator>wrongbyte</dc:creator>
      <pubDate>Thu, 14 Sep 2023 23:33:40 +0000</pubDate>
      <link>https://dev.to/wrongbyte/introduction-to-graphs-bfs-algorithm-mld</link>
      <guid>https://dev.to/wrongbyte/introduction-to-graphs-bfs-algorithm-mld</guid>
      <description>&lt;p&gt;Imagine we have a game in which the characters can move in a 2D grid, just like the image below:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwk5f116s319nxqwolwdb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwk5f116s319nxqwolwdb.png" alt="grid example"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, let's say our character needs to reach the marked square. More importantly, he needs to reach the destination in the &lt;strong&gt;shortest path possible&lt;/strong&gt;, considering that the character &lt;strong&gt;can only move one square horizontally or vertically at a time&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm04lo8jgu3g6g196euue.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm04lo8jgu3g6g196euue.png" alt="character in a grid"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;How can we solve this problem and find the shortest path? The answer lies on graphs.&lt;/p&gt;

&lt;h2&gt;
  
  
  Changing the perspective: seeing the grid as a graph
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxeffwbonvbcbncg7qmpp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxeffwbonvbcbncg7qmpp.png" alt="graph example"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The image above depicts a graph - a visual representation of data or information that consists of &lt;strong&gt;nodes&lt;/strong&gt; (or vertices) connected by &lt;strong&gt;edges&lt;/strong&gt;. Each node represents an &lt;em&gt;entity&lt;/em&gt;, while the edges represent &lt;em&gt;relationships&lt;/em&gt; or &lt;em&gt;connections&lt;/em&gt; between these entities. Graphs can be used to model a wide range of complex systems, such as social networks, transportation networks, computer networks, and more. They are a fundamental data structure in mathematics and computer science, enabling the analysis, visualization, and problem-solving of various real-world scenarios and relationships.&lt;/p&gt;

&lt;p&gt;In our problem, a graph is useful to model the grid - a set of coordinated points representing all possible positions of our character. As we are talking about a movement that can only be &lt;strong&gt;horizontal or vertical&lt;/strong&gt;, each square has adjacent squares that the character can move to, provided they meet the condition of being horizontally or vertically adjacent.&lt;/p&gt;

&lt;p&gt;Therefore, the grid below&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn93xyvxmgxe55wqpo03b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn93xyvxmgxe55wqpo03b.png" alt="grid"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Can be represented by the following graph, in which we can see the nodes and the edges connecting them:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faqa7k09ufgtu5abv6fkv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faqa7k09ufgtu5abv6fkv.png" alt="grid becomes a graph"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This shift of perspective is the first step to solve our problem; the second step is to write an algorithm to "walk the graph"&lt;/p&gt;

&lt;h2&gt;
  
  
  Pathfinding algorithms
&lt;/h2&gt;

&lt;p&gt;Finding the shortest path in a graph is a very common problem encountered in various real-life scenarios - think about GPS navigation systems, for example.&lt;/p&gt;

&lt;p&gt;For this reason, this type of algorithm has been studied for a long time, and nowadays there are multiple ways to solve the problem of "finding the shortest path." The simplest algorithms are &lt;em&gt;Breadth-First Search&lt;/em&gt; (which we'll see in this post) and &lt;em&gt;Depth-First Search&lt;/em&gt;. There are also more advanced (and effective) ones such as &lt;em&gt;Dijkstra&lt;/em&gt; and &lt;em&gt;A*&lt;/em&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  How Breadth-First Search works?
&lt;/h2&gt;

&lt;p&gt;Think about it for a minute: what is the first step to find the shortest path in a maze? &lt;/p&gt;

&lt;p&gt;One possible answer is to first map all the possible paths. After all, to find the shortest path, we first need to know which paths are possible, taking into account the character's movement restrictions.&lt;/p&gt;

&lt;p&gt;We can narrow down the problem scope by asking, "Which squares can my character move to from the current position, denoted as X?"&lt;br&gt;
This is necessary given that, particularly at the edges of the grid, the character may not be able to move further vertically or horizontally. Furthermore, there could be scenarios where the character's movement should be limited by certain conditions, similar to this &lt;a href="https://adventofcode.com/2022/day/12" rel="noopener noreferrer"&gt;Advent of Code problem&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Therefore, let's write a simple function that decides the "available neighbors" (adjacent positions which we can move to), given we are working with coordinates, represented by cartesian points like below:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="n"&gt;Coord&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;usize&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;usize&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;neighbors&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;Grid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;curr_coord&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;Coord&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Coord&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;deltas&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="nb"&gt;isize&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;isize&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)];&lt;/span&gt;

    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;neighbors&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Coord&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;deltas&lt;/span&gt;
        &lt;span class="nf"&gt;.into_iter&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="nf"&gt;.filter_map&lt;/span&gt;&lt;span class="p"&gt;(|(&lt;/span&gt;&lt;span class="n"&gt;dx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dy&lt;/span&gt;&lt;span class="p"&gt;)|&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;coord_x&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;curr_coord&lt;/span&gt;&lt;span class="py"&gt;.x&lt;/span&gt;&lt;span class="nf"&gt;.checked_add_signed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dx&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;coord_y&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;curr_coord&lt;/span&gt;&lt;span class="py"&gt;.y&lt;/span&gt;&lt;span class="nf"&gt;.checked_add_signed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dy&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;neighb_coord&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Coord&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;coord_x&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;coord_y&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;};&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="nf"&gt;.in_bounds&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;neighb_coord&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;None&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="nf"&gt;Some&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;neighb_coord&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;})&lt;/span&gt;
        &lt;span class="nf"&gt;.collect&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

    &lt;span class="n"&gt;neighbors&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This function receives the grid as a parameter. The grid is a struct that contains all the points and info such as height and width:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="n"&gt;Grid&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;width&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;usize&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;height&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;usize&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Coord&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;start_coord&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Coord&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;end_coord&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Coord&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Then, we are going to check all possible four coordinates that are adjacent to the current coordinate. In the code, this is represented by &lt;code&gt;[(-1, 0), (1, 0), (0, -1), (0, 1)]&lt;/code&gt;, which are the numbers we are going to sum with &lt;code&gt;x&lt;/code&gt; and &lt;code&gt;y&lt;/code&gt; to verify squares vertically and horizontally adjacent. &lt;br&gt;
Rust provides a method &lt;code&gt;checked_add_signed&lt;/code&gt;, which is used here to verify if the sum returns a positive number. For example, if we add 0 + (-1), we would get -1, but here Rust returns &lt;code&gt;None&lt;/code&gt; to this operation - which excludes negative (and therefore invalid) coordinates from the neighbors returned by this function. &lt;br&gt;
After excluding possibly negative coordinates, the &lt;code&gt;grid.in_bounds()&lt;/code&gt; method checks if the neighbor coordinates are out of grid bounds:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;in_bounds&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;coord&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;Coord&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;bool&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;coord&lt;/span&gt;&lt;span class="py"&gt;.x&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.width&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;coord&lt;/span&gt;&lt;span class="py"&gt;.y&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.height&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;In sum, the general idea in this step is to get the adjacent coordinates from a grid square and return only the valid ones.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;However, mapping the available positions for each square is not enough: how do we &lt;em&gt;move from square to square?&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Enqueueing the nodes
&lt;/h2&gt;

&lt;p&gt;Walking the graph involves:&lt;br&gt;
1 - Moving to a square&lt;br&gt;
2 - Mapping the available positions from that square&lt;br&gt;
3 - Moving to the next available square&lt;/p&gt;

&lt;p&gt;In code, this can be translated to: put the available nodes in a queue, visit each node mapping its neighbors (and putting them in the queue), store the visited nodes and repeat this sequence until the queue is empty.&lt;/p&gt;

&lt;p&gt;Visually, we can demonstrate it like this (images from GeeksforGeeks):&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftcgwf95ihpk2bitpe5we.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftcgwf95ihpk2bitpe5we.png" alt="first step"&gt;&lt;/a&gt;&lt;br&gt;
We start with an empty queue and an empty array of visited nodes. Once we map the available nodes from that starting point, we populate the queue and mark the start coordinate as visited:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhhakggyddomta86kfeor.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhhakggyddomta86kfeor.png" alt="second step"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;While the queue is not empty, we get the first element from it (that becomes our current node), map their neighbors and add it to the visited array.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fou3v174kqfrl043lez6i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fou3v174kqfrl043lez6i.png" alt="third step"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="nf"&gt;.len&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;curr_node&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="nf"&gt;.pop_front&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.expect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"queue is empty"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;curr_node_neighbors&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;neighbors&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;curr_node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;part&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;neighbor&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;curr_node_neighbors&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="nf"&gt;.contains&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;neighbor&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="nf"&gt;.push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;neighbor&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
                &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="nf"&gt;.push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;neighbor&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Once the queue is empty, we know all possible paths have been checked.&lt;/p&gt;

&lt;h2&gt;
  
  
  All roads lead to Rome
&lt;/h2&gt;

&lt;p&gt;Finding all possible paths our character can walk does not tell us anything about the shortest path to point X. However, we are halfway there.&lt;/p&gt;

&lt;p&gt;Since we guarantee that nodes in &lt;code&gt;visited&lt;/code&gt; vec are not visited again, no node is visited more than once. This constraint guarantees we don't repeat ourselves checking again paths that lead to nowhere. Additionally, BFS employs a queue data structure to keep track of nodes to visit - which means nodes are enqueued in the order they are discovered, and dequeued in the same order. This "first-in, first-out" (FIFO) behavior ensures that nodes closer to the source are explored before nodes farther away.&lt;/p&gt;

&lt;p&gt;Therefore, once BFS reaches the node we are searching for (the destination node), &lt;strong&gt;it has essentially found the shortest path in terms of the number of edges.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Finally, to find the shortest path, we can start from the destination node and follow its parent backward through the graph until we reach the source node.&lt;/p&gt;

&lt;p&gt;To do so, we keep track of the &lt;em&gt;parent node&lt;/em&gt; of each node visited, so that we can reconstruct the path. We can do this using a hashmap, for example, to store coordinates and their respective parents.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;coord_parents&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;Option&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Coord&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;Option&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Coord&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;HashMap&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;new&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And finally, we can add the following logic to recreate the path that leads to the destination node:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;curr_node&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;Some&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="nf"&gt;Some&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current_coord&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="nf"&gt;.push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current_coord&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;coord_parents&lt;/span&gt;&lt;span class="nf"&gt;.get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="nf"&gt;.expect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"coord not found"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Basically, what this code does is populate a Vec named &lt;code&gt;path&lt;/code&gt;, which stores the &lt;code&gt;Coord&lt;/code&gt;s that correspond to the path from the initial node to the final node. As you can see, this &lt;code&gt;Vec&lt;/code&gt; is constructed based on the information of the parent of each node.&lt;/p&gt;

&lt;p&gt;Our code becomes roughly like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;find_path&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;Grid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Coord&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;VecDeque&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Coord&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;VecDeque&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;new&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Coord&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Vec&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;new&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Coord&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Vec&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;new&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;coord_parents&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;Option&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Coord&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;Option&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Coord&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;HashMap&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;new&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

    &lt;span class="c1"&gt;// Populate the initial info&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="py"&gt;.start_coord&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="py"&gt;.end_coord&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;coord_parents&lt;/span&gt;&lt;span class="nf"&gt;.insert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;Some&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="nb"&gt;None&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="nf"&gt;.push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="nf"&gt;.push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="nf"&gt;.len&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;curr_node&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="nf"&gt;.pop_front&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.expect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"queue is empty"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;curr_node&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// We reached the end node, now we reconstruct the path&lt;/span&gt;
            &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;Some&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
            &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="nf"&gt;Some&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current_coord&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="nf"&gt;.push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current_coord&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
                &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;coord_parents&lt;/span&gt;&lt;span class="nf"&gt;.get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="nf"&gt;.expect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"coord not found"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;curr_node_neighbors&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;neighbors&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;grid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;curr_node&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;neighbor&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;curr_node_neighbors&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="nf"&gt;.contains&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;neighbor&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;queue&lt;/span&gt;&lt;span class="nf"&gt;.push_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;neighbor&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
                &lt;span class="n"&gt;visited&lt;/span&gt;&lt;span class="nf"&gt;.push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;neighbor&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
                &lt;span class="n"&gt;coord_parents&lt;/span&gt;&lt;span class="nf"&gt;.insert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;Some&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;neighbor&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="nf"&gt;Some&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;curr_node&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="n"&gt;path&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;




&lt;p&gt;BFS definitely is not the standard for pathfinding nowadays, since it is a lot less efficient than more advanced algorithms, such as A*. However, understanding how BFS works provide us with very useful insights about the importance of graphs and how they can be applied in Computer Science.&lt;/p&gt;

</description>
      <category>algorithms</category>
      <category>computerscience</category>
      <category>gamedev</category>
      <category>rust</category>
    </item>
    <item>
      <title>Beginner's guide to Rust references</title>
      <dc:creator>wrongbyte</dc:creator>
      <pubDate>Sat, 05 Aug 2023 16:32:09 +0000</pubDate>
      <link>https://dev.to/wrongbyte/rust-references-5ehc</link>
      <guid>https://dev.to/wrongbyte/rust-references-5ehc</guid>
      <description>&lt;p&gt;You probably know that this code does not compile&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;my_vec&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nd"&gt;vec!&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;my_other_vec&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;my_vec&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;my_vec&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// error!&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;but this code does:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;my_number&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;my_other_number&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;my_number&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;my_number&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It happens due to the key principle of Rust language: the ownership system. Two main things happen here: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;Vec&amp;lt;T&amp;gt;&lt;/code&gt; does not implement the &lt;code&gt;Copy&lt;/code&gt; trait, so its value will be moved to &lt;code&gt;my_other_vec&lt;/code&gt; and we won't be able to use &lt;code&gt;my_vec&lt;/code&gt; after that.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;i32&lt;/code&gt; does implement the &lt;code&gt;Copy&lt;/code&gt; trait, so its value will be copied to &lt;code&gt;my_other_number&lt;/code&gt;, and we can still use the &lt;code&gt;my_number&lt;/code&gt; variable.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;However, in the real world, we often deal with types that don't implement the Copy trait, and having to move things around multiple times would become a real headache if there was no alternative. But Rust has a way to use values without moving them: borrowing.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;my_vec&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nd"&gt;vec!&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
    &lt;span class="nf"&gt;add_one&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;my_vec&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;add_one&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;i32&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the &lt;code&gt;add_one&lt;/code&gt; function were to accept a Vec instead of a &amp;amp;Vec, any vec passed to this function would be moved into it, rendering the original value unusable. Since this is not the behavior we want, our function now accepts a reference to a value, instead of the value itself.&lt;/p&gt;

&lt;h2&gt;
  
  
  Immutable references (&lt;code&gt;&amp;amp;T&lt;/code&gt;) - reading a value
&lt;/h2&gt;

&lt;p&gt;The previous snippet shows a scenario in which we need to borrow a value only for reading, without modifying it. Just like variables in Rust, which are immutable unless you put the keyword &lt;code&gt;mut&lt;/code&gt; in the declaration, references are also immutable by default.&lt;br&gt;
This behavior guarantees that we do not accidentally change the value, since we are only reading from it. For this reason, we can have as many &lt;strong&gt;immutable&lt;/strong&gt; references as we want - and that's the reason why the type &lt;code&gt;&amp;amp;T&lt;/code&gt; is also called a &lt;strong&gt;shared reference.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;However, the use of immutable references follows some additional rules.&lt;br&gt;
Let's imagine a scenario in which we need to create a &lt;code&gt;Vec&amp;lt;i32&amp;gt;&lt;/code&gt; based on another &lt;code&gt;Vec&amp;lt;i32&amp;gt;&lt;/code&gt;, but we only have access to the reference pointing to the &lt;code&gt;Vec&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;my_vec_ref&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;i32&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;my_vec&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is a type mismatch here, since &lt;code&gt;my_vec_ref&lt;/code&gt; is supposed to be a &lt;code&gt;Vec&lt;/code&gt;, not a &lt;em&gt;reference&lt;/em&gt; to one. However, there is a solution: Rust provides the "inverse" operator of &lt;code&gt;&amp;amp;&lt;/code&gt;: the &lt;code&gt;*&lt;/code&gt; operator, which lets us access the value behind a reference!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;my_vec&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;i32&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nd"&gt;vec!&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;my_vec_ref&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;my_vec&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;another_vec&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;my_vec_ref&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// oops!&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;... but not to move it.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The code above gives us the following error:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cannot move out of `*my_vec_ref` which is behind a shared reference
move occurs because `*my_vec_ref` has type `Vec&amp;lt;i32&amp;gt;`, which does not implement the `Copy` trait
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Alright, we know that &lt;code&gt;Vec&amp;lt;i32&amp;gt;&lt;/code&gt; does not implement the &lt;code&gt;Copy&lt;/code&gt; trait and stuff, but what is this error actually telling us?&lt;/p&gt;

&lt;h3&gt;
  
  
  Moving &lt;em&gt;out&lt;/em&gt;
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;=&lt;/code&gt; operator creates an &lt;em&gt;assignment expression&lt;/em&gt;. According to Rust docs, an assignment expression &lt;em&gt;moves&lt;/em&gt; a value into a specified place.&lt;/p&gt;

&lt;p&gt;Things are pretty straightforward when we are dealing with straightforward types, but a reference is what we call an &lt;em&gt;indirection type&lt;/em&gt; - a type that has a "layer" between you and the real data. In this case, we can imagine the reference as a &lt;em&gt;wrapper&lt;/em&gt; for the data. Due to its immutability, we are not allowed to either &lt;strong&gt;change&lt;/strong&gt; what's inside of it or &lt;strong&gt;move&lt;/strong&gt; what's inside of it. In other words, we can't &lt;strong&gt;"move out"&lt;/strong&gt;.&lt;br&gt;
It also implies that we can only move things from values &lt;strong&gt;we own&lt;/strong&gt;, never from values we &lt;strong&gt;borrow&lt;/strong&gt; - which is another way to say the same thing.&lt;/p&gt;

&lt;p&gt;Additionally, in Rust the &lt;code&gt;.&lt;/code&gt; operator automatically dereferences reference types, causing the same error to happen when we try to do things such as the code below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="n"&gt;MyStruct&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;str_vec&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;i32&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;strct&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;MyStruct&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;str_vec&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nd"&gt;vec!&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;]};&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;strct_ref&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;strct&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;my_vec&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;strct_ref&lt;/span&gt;&lt;span class="py"&gt;.str_vec&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// error!&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This behavior is useful when talking about methods that take &lt;code&gt;self&lt;/code&gt; by reference, ommiting the use of &lt;code&gt;*&lt;/code&gt; operator:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="n"&gt;MyStruct&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;u32&lt;/span&gt; &lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="k"&gt;impl&lt;/span&gt; &lt;span class="n"&gt;MyStruct&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// no need to type (*self).n&lt;/span&gt;
    &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;method&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;u32&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.n&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;MyStruct&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;12&lt;/span&gt; &lt;span class="p"&gt;};&lt;/span&gt;
&lt;span class="c1"&gt;// Here the compiler automatically references self,&lt;/span&gt;
&lt;span class="c1"&gt;// so that there's no need to write (&amp;amp;x).method()&lt;/span&gt;
&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="nf"&gt;.method&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  The solution
&lt;/h3&gt;

&lt;p&gt;Back to one of our previous examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;my_vec&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;i32&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nd"&gt;vec!&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;my_vec_ref&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;my_vec&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;another_vec&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;i32&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;my_vec_ref&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// oops!&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In cases like this, the error messages may contain some misleading instructions, such as the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;consider borrowing here: `&amp;amp;*my_vec_ref
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is not possible here, since it means assigning a &lt;code&gt;&amp;amp;Vec&amp;lt;i32&amp;gt;&lt;/code&gt; to a value that has type &lt;code&gt;Vec&amp;lt;i32&amp;gt;&lt;/code&gt;.&lt;br&gt;&lt;br&gt;
Therefore, the solution when this error happens is to &lt;em&gt;clone&lt;/em&gt; the value - so that you get a copy from it without moving it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;another_vec&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;i32&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;my_vec_ref&lt;/span&gt;&lt;span class="nf"&gt;.clone&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Mutable references (&lt;code&gt;&amp;amp;mut T&lt;/code&gt;)
&lt;/h2&gt;

&lt;p&gt;Modifying a non-copy value follows the logic of moving or borrowing. You can either move the value in order to modify it, or use a &lt;strong&gt;mutable reference&lt;/strong&gt; (borrow) to do so.&lt;br&gt;
Let's create a function that modifies a value using a &lt;code&gt;&amp;amp;mut T&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;my_vec&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nd"&gt;vec!&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;ref_my_vec&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;my_vec&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nf"&gt;add_one&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ref_my_vec&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;my_vec&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;add_one&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;i32&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
    &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="nf"&gt;.push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When we assign a mutable reference to &lt;code&gt;ref_my_vec&lt;/code&gt;, it means that this variable &lt;em&gt;points to&lt;/em&gt; an &lt;strong&gt;existing&lt;/strong&gt; value, instead of owning a new value. Therefore, modifying &lt;code&gt;ref_my_vec&lt;/code&gt; is equivalent to directly modify &lt;code&gt;my_vec&lt;/code&gt;. We can say that a mutable reference provides us with write access to a value. &lt;br&gt;
However, since the only way to &lt;em&gt;securely&lt;/em&gt; modify a value is to have an &lt;strong&gt;unique write access&lt;/strong&gt; to it (think about data races), Rust does not allow us to have more than one mutable reference to the same value simultaneously.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;ref_my_vec&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;my_vec&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;another_ref&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;my_vec&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="c1"&gt;// cannot borrow `my_vec` as mutable more than once at a time&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the reason why a mutable reference is also called an &lt;strong&gt;unique reference.&lt;/strong&gt; &lt;br&gt;
Similarly to shared references, Rust also does not allow us to move &lt;em&gt;out&lt;/em&gt; of mutable references. In fact, moving out from any kind of reference - mutable or not - &lt;strong&gt;is not allowed&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;my_vec&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;i32&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nd"&gt;vec!&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;my_vec_ref&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;my_vec&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;another_vec&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;my_vec_ref&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// oops!&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cannot move out of `*my_vec_ref` which is behind a mutable reference
move occurs because `*my_vec_ref` has type `Vec&amp;lt;i32&amp;gt;`, which does not implement the `Copy` trait
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Mutability with references
&lt;/h2&gt;

&lt;h3&gt;
  
  
  What is the difference between &lt;code&gt;p: &amp;amp;T&lt;/code&gt;, &lt;code&gt;mut p: &amp;amp;T&lt;/code&gt;, &lt;code&gt;p: &amp;amp;mut T&lt;/code&gt; and &lt;code&gt;mut p: &amp;amp;mut T&lt;/code&gt;?
&lt;/h3&gt;

&lt;p&gt;When talking about a variable whose type is a reference, it is important to differentiate what does it mean to change what &lt;em&gt;the reference points to&lt;/em&gt; and what &lt;em&gt;our variable points to.&lt;/em&gt;&lt;br&gt;
Therefore, you can do the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;vec_number&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nd"&gt;vec!&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;another_vec&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nd"&gt;vec!&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;ref_vec&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;vec_number&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;ref_vec&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;another_vec&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's see what is happening here. &lt;br&gt;
Although we &lt;em&gt;cannot&lt;/em&gt; change the data the &lt;code&gt;ref_vec&lt;/code&gt; variable points to, we can make &lt;code&gt;ref_vec&lt;/code&gt; point to another data (as long as it has the same type of the data previously assigned). &lt;br&gt;
Therefore, when we put the &lt;code&gt;mut&lt;/code&gt; keyword in the &lt;strong&gt;left side&lt;/strong&gt; of an &lt;em&gt;assignment expression&lt;/em&gt;, we are telling Rust that we are going to reassign that variable to another value.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Type&lt;/th&gt;
&lt;th&gt;Can reassign the variable&lt;/th&gt;
&lt;th&gt;Can change the data the variable points to&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;p: &amp;amp;T&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;mut p: &amp;amp;T&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;p: &amp;amp;mut T&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;mut p: &amp;amp;mut T&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

</description>
      <category>rust</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Implementing Iterator and IntoIterator in Rust</title>
      <dc:creator>wrongbyte</dc:creator>
      <pubDate>Tue, 25 Apr 2023 23:13:22 +0000</pubDate>
      <link>https://dev.to/wrongbyte/implementing-iterator-and-intoiterator-in-rust-3nio</link>
      <guid>https://dev.to/wrongbyte/implementing-iterator-and-intoiterator-in-rust-3nio</guid>
      <description>&lt;p&gt;Iterators are a powerful tool that allow for efficient iteration over data structures, and they are implemented in many programming languages - including Rust. However, Rust's unique ownership system gives rise to interesting differences in how iterators are implemented and used. In this article, we will explore these differences and delve into Rust's features by creating and implementing the most commonly used iterator traits - &lt;code&gt;Iterator&lt;/code&gt; and &lt;code&gt;IntoIterator&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;


&lt;p&gt;Imagine you have a structure like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="n"&gt;Todos&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Todo&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The struct above is a &lt;code&gt;Vec&amp;lt;Todo&amp;gt;&lt;/code&gt;, which is a vector of &lt;code&gt;Todos&lt;/code&gt;, which have this structure:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="n"&gt;Todo&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="n"&gt;done&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;bool&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we wish to iterate over each &lt;code&gt;Todo&lt;/code&gt; in this &lt;code&gt;Vec&lt;/code&gt;, we could simply use its &lt;code&gt;list&lt;/code&gt; property and iterate over its items, right?&lt;br&gt;
But what if we wanted to iterate over &lt;code&gt;Todos&lt;/code&gt; itself, without exposing its internal properties?&lt;br&gt;
&lt;em&gt;That's where things start to get interesting...&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  What is an iterator?
&lt;/h2&gt;

&lt;p&gt;An iterator is a pattern that allows you to go through each element in an &lt;em&gt;iterable&lt;/em&gt; sequentially. Iterators are very useful in loops, allowing you to iterate over items in a neat way.&lt;br&gt;
Let's see a loop without and with iterators, in Javascript:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;array&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;

&lt;span class="c1"&gt;// without iterators&lt;/span&gt;
&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="nx"&gt;array&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;length&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;array&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// with iterators; "item" is the iterator&lt;/span&gt;
&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt; &lt;span class="k"&gt;of&lt;/span&gt; &lt;span class="nx"&gt;array&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, they are present in a lot of other languages, as Javascript, Python and so on.&lt;/p&gt;

&lt;h2&gt;
  
  
  Iterators in Rust
&lt;/h2&gt;

&lt;p&gt;In Rust, similarly with languages such as Python, iterators are &lt;em&gt;lazy&lt;/em&gt;. It means that they are effectless unless you iterate over them (a.k.a consume them).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nd"&gt;vec!&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;numbers_iter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="nf"&gt;.iter&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code above creates an iterator - and does &lt;em&gt;nothing&lt;/em&gt; with it.&lt;br&gt;
To use the iterator, we should create a for loop, for example as it follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nd"&gt;vec!&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;numbers_iter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt;&lt;span class="nf"&gt;.iter&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;number&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;numbers&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;number&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are also other ways which we can use to create iterators. For example, every time we use &lt;code&gt;map()&lt;/code&gt; in Rust we are creating an iterator.&lt;/p&gt;

&lt;h3&gt;
  
  
  Iterators vs Iterables
&lt;/h3&gt;

&lt;p&gt;A vector, as seen before, is an iterable. &lt;br&gt;
It means that we can iterate over them; but more precisely, it means that &lt;em&gt;we can use a Vec to create an Iterator&lt;/em&gt;. This is the definition of an iterable - some object with which we can create an Iterator. For example, a &lt;code&gt;Vec&amp;lt;u32&amp;gt;&lt;/code&gt; can produce an iterator - &lt;strong&gt;but is not an iterator itself&lt;/strong&gt;.&lt;/p&gt;
&lt;h3&gt;
  
  
  Creating an Iterator
&lt;/h3&gt;

&lt;p&gt;Okay, let's go back to our &lt;code&gt;Todos&lt;/code&gt; struct and see how could we create a way to iterate over its items.&lt;br&gt;
&lt;code&gt;Todos&lt;/code&gt; has a field &lt;code&gt;list&lt;/code&gt;, which is a &lt;code&gt;Vec&amp;lt;Todos&amp;gt;&lt;/code&gt;. &lt;br&gt;
In Rust, Iterator is a &lt;em&gt;trait&lt;/em&gt; which has some methods in it, such as &lt;code&gt;next()&lt;/code&gt;, which is responsible for taking the next element of the collection and returning it, or returning &lt;code&gt;None&lt;/code&gt; if we've already reached the end of the collection. Its implemention looks roughly like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;trait&lt;/span&gt; &lt;span class="nb"&gt;Iterator&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;type&lt;/span&gt; &lt;span class="n"&gt;Item&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Option&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;Self&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Item&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Fine. We could, then, create a way to iterate over the elements of the &lt;code&gt;list&lt;/code&gt; field of our &lt;code&gt;Todos&lt;/code&gt;, writing a custom &lt;code&gt;next()&lt;/code&gt; function. The logic for this is simple - we could do something like this, in pseudocode:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="n"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;next&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;index&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="nf"&gt;.len&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;todo&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;Some&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
        &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.index&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;todo&lt;/span&gt; 
    &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;None&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the logic above, we check for the index of the element and return it, given its index is less than the list length.&lt;br&gt;
&lt;em&gt;But we have a problem here.&lt;/em&gt; Where to store &lt;code&gt;index&lt;/code&gt;?&lt;/p&gt;
&lt;h3&gt;
  
  
  Storing state
&lt;/h3&gt;

&lt;p&gt;That's when the difference between an iterator and an iterable comes into hand. &lt;br&gt;
Translating the pseudocode above, one could implement the &lt;code&gt;next()&lt;/code&gt; function in &lt;code&gt;Todos&lt;/code&gt; like this, implementing a method from the &lt;code&gt;Iterator&lt;/code&gt; trait,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;impl&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nv"&gt;'a&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Iterator&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;Todos&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;type&lt;/span&gt; &lt;span class="n"&gt;Item&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nv"&gt;'a&lt;/span&gt; &lt;span class="n"&gt;Todo&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Option&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;Self&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Item&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.index&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.list&lt;/span&gt;&lt;span class="nf"&gt;.len&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;Some&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.index&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
            &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.index&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="n"&gt;result&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nb"&gt;None&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;But it would require us to change the structure of our &lt;code&gt;Todos&lt;/code&gt;&lt;/strong&gt;: we would need to add a &lt;code&gt;index&lt;/code&gt; field in it to use every time we call &lt;code&gt;next()&lt;/code&gt; - which is, every time we iterate over its items through an iterator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="n"&gt;Todos&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Todo&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;usize&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this logic, we would modify the constructor function in order to always create the struct with &lt;code&gt;index: 0&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;new&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Vec&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Todo&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;Self&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;Todos&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;list&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, this approach simply &lt;em&gt;does not feel right...&lt;/em&gt; &lt;br&gt;
Storing an index field in your &lt;em&gt;struct&lt;/em&gt; is not ideal; the index is used for storing the current state in an iterator, so it should be part of the &lt;em&gt;iterator&lt;/em&gt;, not of the &lt;em&gt;struct&lt;/em&gt;. This is why we are going to create an iterator type - which is going to store the index property - and implement the &lt;code&gt;Iterator&lt;/code&gt; trait for this type. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;The iterator is a type that abstracts the logic of iterating over an iterable; it also stores the current state of iteration, such as the index property.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h1&gt;
  
  
  &lt;code&gt;TodoIterator&lt;/code&gt;
&lt;/h1&gt;

&lt;p&gt;Let's create our iterator then!&lt;br&gt;
First of all, we need to create the type of the iterator:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="n"&gt;TodosIterator&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nv"&gt;'a&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;todos&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nv"&gt;'a&lt;/span&gt; &lt;span class="n"&gt;Todos&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;usize&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note the lifetime annotations here.&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;TodosIterator&lt;/code&gt; has a field &lt;code&gt;todos&lt;/code&gt;, which &lt;em&gt;references&lt;/em&gt; a &lt;code&gt;Todos&lt;/code&gt;. As we are dealing with a &lt;em&gt;reference&lt;/em&gt;, we need to ensure that this field points to something valid - and here lifetime parameters come at hand. The struct &lt;code&gt;TodosIterator&lt;/code&gt; is generic over this lifetime, &lt;code&gt;'a'&lt;/code&gt;.&lt;br&gt;
Basically, we are using this notation to specify that the &lt;code&gt;todos&lt;/code&gt; field of the iterator needs to have &lt;em&gt;the same lifetime&lt;/em&gt; as the data it is pointing to. This way, we ensure that it cannot reference a &lt;code&gt;Todos&lt;/code&gt; struct that has been dropped.&lt;/p&gt;
&lt;h2&gt;
  
  
  Implementing Iterator for &lt;code&gt;TodosIterator&lt;/code&gt;
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="c1"&gt;// ps: it could be done using .get() as well, however I wanted to use this approach to make it a bit more clear how Options are returned in this context &lt;/span&gt;
&lt;span class="k"&gt;impl&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nv"&gt;'a&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Iterator&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;TodosIterator&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nv"&gt;'a&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;type&lt;/span&gt; &lt;span class="n"&gt;Item&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nv"&gt;'a&lt;/span&gt; &lt;span class="n"&gt;Todo&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Option&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;Self&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Item&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.index&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.todos.list&lt;/span&gt;&lt;span class="nf"&gt;.len&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;Some&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.todos.list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.index&lt;/span&gt;&lt;span class="p"&gt;]);&lt;/span&gt;
            &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.index&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="n"&gt;result&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nb"&gt;None&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;em&gt;Now&lt;/em&gt;, we are doing it right.&lt;br&gt;
In the implementation of this trait, we specify the same lifetime used for the struct. It means that &lt;strong&gt;the implementation is tied to the lifetime of the struct&lt;/strong&gt; - which is necessary because we are returning a reference in the &lt;code&gt;next()&lt;/code&gt; method.&lt;/p&gt;
&lt;h3&gt;
  
  
  How to use this iterator?
&lt;/h3&gt;

&lt;p&gt;Now we have already created the &lt;code&gt;TodoIterator&lt;/code&gt; struct as well as implemented the &lt;code&gt;Iterator&lt;/code&gt; trait for this struct, how do we use it to iterate over &lt;code&gt;Todos&lt;/code&gt;?&lt;br&gt;
The answer lies on the &lt;code&gt;iter()&lt;/code&gt; method. This method takes a reference of our &lt;code&gt;Todos&lt;/code&gt; and uses it to create an iterator, which we can use to iterate!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;impl&lt;/span&gt; &lt;span class="n"&gt;Todos&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;iter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;TodosIterator&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;TodosIterator&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;todos&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Now we can iterate:&lt;/span&gt;
&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;todo&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;todos&lt;/span&gt;&lt;span class="nf"&gt;.iter&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;todo&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// each todo is a &amp;amp;Todo, and is immutable&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  IntoIterator
&lt;/h2&gt;

&lt;p&gt;IntoIterator is a bit different from the &lt;code&gt;Iterator&lt;/code&gt; trait. Its single method, &lt;code&gt;into_iter()&lt;/code&gt;, returns an iterator over some data and &lt;strong&gt;makes it possible to iterate over data in a generic way, regardless of its actual type&lt;/strong&gt;. It happens because &lt;em&gt;all types that implement &lt;code&gt;IntoIterator&lt;/code&gt; can be converted into an iterator.&lt;/em&gt; &lt;/p&gt;

&lt;p&gt;Let's understand its implementation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;trait&lt;/span&gt; &lt;span class="nb"&gt;IntoIterator&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;type&lt;/span&gt; &lt;span class="n"&gt;Item&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;type&lt;/span&gt; &lt;span class="n"&gt;IntoIter&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Iterator&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Item&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;Self&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Item&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;into_iter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;Self&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;IntoIter&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Some important points here:&lt;br&gt;
1 - The &lt;code&gt;Item&lt;/code&gt; type parameter is the type of the elements that the iterator will yield.&lt;br&gt;
2 - The &lt;code&gt;IntoIter&lt;/code&gt; type parameter is the type of the iterator that will be returned by the &lt;code&gt;into_iter&lt;/code&gt; method. &lt;strong&gt;This type must implement the &lt;code&gt;Iterator&lt;/code&gt; trait, and the type of its &lt;code&gt;Item&lt;/code&gt; must be the same as the &lt;code&gt;Item&lt;/code&gt; of &lt;code&gt;IntoIterator&lt;/code&gt;.&lt;/strong&gt;&lt;br&gt;
3 - The &lt;code&gt;into_iter&lt;/code&gt; method takes &lt;code&gt;self&lt;/code&gt; as an argument, meaning &lt;strong&gt;it consumes the original object&lt;/strong&gt; and returns an iterator over its elements.&lt;/p&gt;

&lt;p&gt;Ok, how to implement it?&lt;br&gt;
You may think we could &lt;em&gt;reuse&lt;/em&gt; the &lt;code&gt;TodosIterator&lt;/code&gt; - however, we can't since it takes a &lt;code&gt;&amp;amp;Todos&lt;/code&gt;, and we need to &lt;em&gt;take ownership&lt;/em&gt; of the iterable. So let's create another iterator that does it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="n"&gt;TodosIntoIterator&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;todos&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Todos&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The difference between &lt;code&gt;TodosIntoIterator&lt;/code&gt; and &lt;code&gt;TodosIterator&lt;/code&gt; is that here we are not using a &lt;em&gt;reference&lt;/em&gt;, but taking ownership and returning each item itself - that why we also don't need the lifetime annotations anymore. And also there's no index to keep the state, we soon are going to see why.&lt;/p&gt;

&lt;p&gt;Following the definition of the trait &lt;code&gt;IntoIterator&lt;/code&gt;, we can implement it for &lt;code&gt;Todos&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;impl&lt;/span&gt; &lt;span class="nb"&gt;IntoIterator&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;Todos&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;type&lt;/span&gt; &lt;span class="n"&gt;Item&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Todo&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;type&lt;/span&gt; &lt;span class="n"&gt;IntoIter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;TodosIntoIterator&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;into_iter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;TodosIntoIterator&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;TodosIntoIterator&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;todos&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, before doing it, we need to implement &lt;code&gt;Iterator&lt;/code&gt; for &lt;code&gt;TodosIntoIterator&lt;/code&gt; (remember the type parameters?) to describe how we are going to iterate over it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;impl&lt;/span&gt; &lt;span class="nb"&gt;Iterator&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;TodosIntoIterator&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;type&lt;/span&gt; &lt;span class="n"&gt;Item&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Todo&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Option&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;Self&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Item&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.todos.list&lt;/span&gt;&lt;span class="nf"&gt;.len&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;None&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.todos.list&lt;/span&gt;&lt;span class="nf"&gt;.remove&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nf"&gt;Some&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This implementation is a bit different from what we've done for &lt;code&gt;TodosIterator&lt;/code&gt;. We are taking advantage of the &lt;code&gt;remove()&lt;/code&gt; method that exists for &lt;code&gt;Vec&lt;/code&gt;s in Rust. This method removes the item at the position &lt;code&gt;n&lt;/code&gt; and returns it to us, giving the ownership (which is necessary to return a &lt;code&gt;Todo&lt;/code&gt; instead of a &lt;code&gt;&amp;amp;Todo&lt;/code&gt;). Due to how this method works, we can always use "0" to return the first element, instead of storing a state and increasing it sequentially.&lt;br&gt;
Using &lt;code&gt;remove&lt;/code&gt; also guarantees that we are going to yield each value exactly once while also not keeping values already returned in the state of the iterator.&lt;/p&gt;

&lt;p&gt;And now, we are done! These two implementations make it possible for us to iterate over a &lt;code&gt;Todos&lt;/code&gt; in two different ways:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;By reference (&amp;amp;Todos)
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;todo&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;todo_list&lt;/span&gt;&lt;span class="nf"&gt;.iter&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;todo&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="c1"&gt;// todo is a &amp;amp;Todo&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// we can reuse todo_list, since it's not consumed&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Taking ownership:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;todo&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;todo_list&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;todo&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// todo is a Todo&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// we cannot reuse todo_list, since the for loop consumes it&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>rust</category>
      <category>beginners</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>How to deploy a function in Google Cloud with Terraform</title>
      <dc:creator>wrongbyte</dc:creator>
      <pubDate>Fri, 03 Feb 2023 16:58:51 +0000</pubDate>
      <link>https://dev.to/wrongbyte/deploying-a-function-in-google-cloud-with-terraform-1hj0</link>
      <guid>https://dev.to/wrongbyte/deploying-a-function-in-google-cloud-with-terraform-1hj0</guid>
      <description>&lt;p&gt;Previously, &lt;a href="https://dev.to/wrongbyte/how-to-deploy-a-function-in-google-cloud-45h8"&gt;we've deployed a cloud function in Google Cloud&lt;/a&gt;. We have done it through the GCP's command line utility.&lt;br&gt;
Now, we can create and run the same Cloud Function using Terraform.&lt;/p&gt;
&lt;h3&gt;
  
  
  Why to use Terraform?
&lt;/h3&gt;

&lt;p&gt;When we deployed our function using Google's SDK directly, we had to use a command with several flags that could be grouped together in a &lt;code&gt;deploy.sh&lt;/code&gt; script:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;gcloud functions deploy &lt;span class="nv"&gt;$FN_NAME&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--entry-point&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nv"&gt;$FN_ENTRY_POINT&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--runtime&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;nodejs16 &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--region&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;us-central1 &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--trigger-http&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--allow-unauthenticated&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this script, we are specifying &lt;em&gt;exactly&lt;/em&gt; how we want our cloud function to be. The flags specify the entrypoint, the runtime, region, trigger and etc.&lt;/p&gt;

&lt;p&gt;One could say we are &lt;em&gt;describing&lt;/em&gt; how our infrastructure should be. Exactly what we could do with infrastructure as code - in this case, using Terraform!&lt;/p&gt;

&lt;h2&gt;
  
  
  Creating a &lt;code&gt;main.tf&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;main.tf&lt;/code&gt; file is the starting point for Terraform to build and manage your infrastructure.&lt;/p&gt;

&lt;p&gt;We can start by adding a &lt;em&gt;provider&lt;/em&gt;.  A provider is a plugin that lets you use the API operations of a specific cloud provider or service, such as AWS, Google Cloud, Azure etc.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight hcl"&gt;&lt;code&gt;&lt;span class="nx"&gt;provider&lt;/span&gt; &lt;span class="s2"&gt;"google"&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;project&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"project_name"&lt;/span&gt;
    &lt;span class="nx"&gt;region&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"us-central1"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But let's think about the following scenario: what if you wanted to create a &lt;em&gt;generic template&lt;/em&gt; infrastructure that could be reused for different projects other than &lt;code&gt;project_name&lt;/code&gt;?&lt;br&gt;
Here it comes the &lt;code&gt;tfvars&lt;/code&gt; file: a file in which you can put all your environment variables:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;google_project = "project_name"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And now you can use this variable in your &lt;code&gt;main.tf&lt;/code&gt; (you also need to add a block telling Terraform you've declared a variable somewhere else):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight hcl"&gt;&lt;code&gt;&lt;span class="nx"&gt;variable&lt;/span&gt; &lt;span class="s2"&gt;"google_project_name"&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;

&lt;span class="nx"&gt;provider&lt;/span&gt; &lt;span class="s2"&gt;"google"&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;project&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"${var.project_name}"&lt;/span&gt;
    &lt;span class="nx"&gt;region&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"us-central1"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, let's start to add the infrastructure specific to our project!&lt;/p&gt;

&lt;h2&gt;
  
  
  Terraform &lt;code&gt;resource&lt;/code&gt;s
&lt;/h2&gt;

&lt;p&gt;A Terraform resource is a &lt;strong&gt;unit of Terraform configuration that represents a real-world infrastructure object&lt;/strong&gt;, such as an EC2 instance, an S3 bucket, or a virtual network. In our case, we are going to represent a cloud function.&lt;br&gt;
We define these resources in blocks, where we &lt;strong&gt;describe the desired state of the resource&lt;/strong&gt; - including properties such as the type, name, and other configuration options.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Understanding how state works is important because, every time Terraform applies changes to the infrastructure of our projects, &lt;strong&gt;it updates resources to match the desired state defined in the Terraform configuration.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;
  
  
  What's inside a &lt;code&gt;resource&lt;/code&gt;?
&lt;/h3&gt;

&lt;p&gt;Besides the definition previously mentioned, a Terraform resource is - syntatically - a block compound of three parts:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  The type of the resource, such as &lt;code&gt;aws_instance&lt;/code&gt; or &lt;code&gt;google_compute_instance&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  The name of the resource, &lt;strong&gt;which must be unique within the Terraform configuration.&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;  Configuration options for the resource (the &lt;em&gt;state&lt;/em&gt;, as said before), such as the image ID for an EC2 instance or the bucket name for an S3 bucket.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Alright. We are getting there.&lt;br&gt;
Let's then create the &lt;code&gt;resource&lt;/code&gt; block for our Google Cloud Function!&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Each resource block has its specific properties. You can find them in the docs of the Terraform provider you are using. For example, here is the docs for the cloud function we'll be creating:&lt;br&gt;
&lt;a href="https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/cloudfunctions_function" rel="noopener noreferrer"&gt;https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/cloudfunctions_function&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We can start by defining a few things, such as the &lt;code&gt;name&lt;/code&gt;, &lt;code&gt;description&lt;/code&gt; and &lt;code&gt;runtime&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight hcl"&gt;&lt;code&gt;&lt;span class="nx"&gt;resource&lt;/span&gt; &lt;span class="s2"&gt;"google_cloudfunctions_function"&lt;/span&gt; &lt;span class="s2"&gt;"my_function"&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"my_function"&lt;/span&gt;
    &lt;span class="nx"&gt;description&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"the function we are going to deploy"&lt;/span&gt;
    &lt;span class="nx"&gt;runtime&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"nodejs16"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Note: you may have noticed that we are repeating &lt;code&gt;my_function&lt;/code&gt; twice here.&lt;br&gt;
It happens because we have to set a &lt;em&gt;name for the resource&lt;/em&gt; - in this case, &lt;code&gt;my_function&lt;/code&gt;, which is translated to &lt;code&gt;google_cloudfunctions_function.my_function&lt;/code&gt; in Terraform - and we also have to set the value of the &lt;em&gt;name field&lt;/em&gt; of the block, which is going to be used by Google - not Terraform - to identify your function.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  The source code
&lt;/h2&gt;

&lt;p&gt;However, even though we know these basic properties of our function, &lt;em&gt;where is the source code?&lt;/em&gt; In the previous tutorial, Google SDK was able to look into our root directory to find our &lt;code&gt;index.js&lt;/code&gt; file. But here, we only have a Terraform file which specifies our desired state, but no mentions at all about where to find the source code for our function. Let's fix it.&lt;/p&gt;

&lt;h3&gt;
  
  
  Creating a bucket
&lt;/h3&gt;

&lt;p&gt;From the docs, we know we have several ways available to specify in our resource block where to find the source code of our function. Let's do it with a storage bucket.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight hcl"&gt;&lt;code&gt;&lt;span class="nx"&gt;resource&lt;/span&gt; &lt;span class="s2"&gt;"google_storage_bucket"&lt;/span&gt; &lt;span class="s2"&gt;"source_bucket"&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"function-bucket"&lt;/span&gt;
    &lt;span class="nx"&gt;location&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"us-central1"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have a bucket, but we also need a bucket &lt;em&gt;object&lt;/em&gt; that stores our source code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight hcl"&gt;&lt;code&gt;&lt;span class="nx"&gt;resource&lt;/span&gt; &lt;span class="s2"&gt;"google_storage_bucket_object"&lt;/span&gt; &lt;span class="s2"&gt;"source_code"&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"object-name"&lt;/span&gt;
    &lt;span class="nx"&gt;bucket&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;google_storage_bucket&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;bucket&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;
    &lt;span class="nx"&gt;source&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"path/to/local/file"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note the &lt;em&gt;source&lt;/em&gt; field.&lt;br&gt;
Accordingly to the docs, we need to use a &lt;code&gt;.zip&lt;/code&gt; file to store the source code (as well as other files such as &lt;code&gt;package.json&lt;/code&gt;). We can &lt;em&gt;transform&lt;/em&gt; our directory into a &lt;code&gt;zip&lt;/code&gt; file using a &lt;code&gt;data "archive_file"&lt;/code&gt; block:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight hcl"&gt;&lt;code&gt;&lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="s2"&gt;"archive_file"&lt;/span&gt; &lt;span class="s2"&gt;"my_function_zip"&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;type&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"zip"&lt;/span&gt;
    &lt;span class="nx"&gt;source_dir&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"${path.module}/src"&lt;/span&gt;
    &lt;span class="nx"&gt;output_path&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"${path.module}/src.zip"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;path.module&lt;/code&gt; is the filesystem path of the module where the expression is placed.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Therefore, now our &lt;code&gt;main.tf&lt;/code&gt; looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight hcl"&gt;&lt;code&gt;&lt;span class="nx"&gt;variable&lt;/span&gt; &lt;span class="s2"&gt;"google_project_name"&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;

&lt;span class="nx"&gt;provider&lt;/span&gt; &lt;span class="s2"&gt;"google"&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;project&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"${var.google_project_name}"&lt;/span&gt;
    &lt;span class="nx"&gt;region&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"us-central1"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="s2"&gt;"archive_file"&lt;/span&gt; &lt;span class="s2"&gt;"my_function_zip"&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;type&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"zip"&lt;/span&gt;
    &lt;span class="nx"&gt;source_dir&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"${path.module}/src"&lt;/span&gt;
    &lt;span class="nx"&gt;output_path&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"${path.module}/src.zip"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;resource&lt;/span&gt; &lt;span class="s2"&gt;"google_cloudfunctions_function"&lt;/span&gt; &lt;span class="s2"&gt;"my_function"&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"myFunction"&lt;/span&gt;
    &lt;span class="nx"&gt;description&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"the function we are going to deploy"&lt;/span&gt;
    &lt;span class="nx"&gt;runtime&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"nodejs16"&lt;/span&gt;
    &lt;span class="nx"&gt;trigger_http&lt;/span&gt;     &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
    &lt;span class="nx"&gt;ingress_settings&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"ALLOW_ALL"&lt;/span&gt;
    &lt;span class="nx"&gt;source_archive_bucket&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;google_storage_bucket&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;function_source_bucket&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;
    &lt;span class="nx"&gt;source_archive_object&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;google_storage_bucket_object&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;function_source_bucket_object&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;resource&lt;/span&gt; &lt;span class="s2"&gt;"google_storage_bucket"&lt;/span&gt; &lt;span class="s2"&gt;"function_source_bucket"&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"function-bucket"&lt;/span&gt;
  &lt;span class="nx"&gt;location&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"us-central1"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;resource&lt;/span&gt; &lt;span class="s2"&gt;"google_storage_bucket_object"&lt;/span&gt; &lt;span class="s2"&gt;"function_source_bucket_object"&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;name&lt;/span&gt;   &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"function-bucket-object"&lt;/span&gt;
  &lt;span class="nx"&gt;bucket&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;google_storage_bucket&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;function_source_bucket&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;
  &lt;span class="nx"&gt;source&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;archive_file&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;my_function_zip&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;output_path&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can deploy! But... There's still some things missing.&lt;/p&gt;

&lt;p&gt;Using Google SDK we were able to get the URL of our function - since it has a HTTP trigger. It would be good to get this URL right away.&lt;br&gt;
Also, we needed to set IAM policies to let everyone trigger our function. How to do something similar in Terraform?&lt;/p&gt;

&lt;p&gt;We can fix these things by adding two blocks: one which is for IAM policies and another to display the output - an output block.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In Terraform, an output block is used to define the desired values that should be displayed when Terraform applies changes to infrastructure.&lt;br&gt;
If we run &lt;code&gt;terraform plan&lt;/code&gt; right now, we can see some properties that will be known once the infrastructure is created. And &lt;code&gt;https_trigger_url&lt;/code&gt; is exactly what we are looking for!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmjk05r60um32uzd097j5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmjk05r60um32uzd097j5.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;


&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight hcl"&gt;&lt;code&gt;&lt;span class="nx"&gt;output&lt;/span&gt; &lt;span class="s2"&gt;"function_url_trigger"&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;value&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;google_cloudfunctions_function&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;my_function&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;https_trigger_url&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;resource&lt;/span&gt; &lt;span class="s2"&gt;"google_cloudfunctions_function_iam_member"&lt;/span&gt; &lt;span class="s2"&gt;"my_second_fn_iam"&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;cloud_function&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;google_cloudfunctions_function&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;my_function&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;
  &lt;span class="nx"&gt;member&lt;/span&gt;         &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"allUsers"&lt;/span&gt;
  &lt;span class="nx"&gt;role&lt;/span&gt;           &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"roles/cloudfunctions.invoker"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, we can run &lt;code&gt;terraform apply&lt;/code&gt; and get, as the output, the URL that triggers our function:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjhye8kee09l8mntkg495.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjhye8kee09l8mntkg495.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And finally, we can trigger it:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0deseeh6av9y6qww9syl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0deseeh6av9y6qww9syl.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;Still feel like you missed something? Take a look on the source code for this tutorial: &lt;a href="https://github.com/wrongbyte-lab/tf-gcp-tutorial" rel="noopener noreferrer"&gt;https://github.com/wrongbyte-lab/tf-gcp-tutorial&lt;/a&gt;&lt;/p&gt;

</description>
      <category>googlecloud</category>
      <category>terraform</category>
      <category>devops</category>
      <category>webdev</category>
    </item>
    <item>
      <title>How to deploy a Cloud Function in Google Cloud</title>
      <dc:creator>wrongbyte</dc:creator>
      <pubDate>Mon, 30 Jan 2023 21:48:50 +0000</pubDate>
      <link>https://dev.to/wrongbyte/how-to-deploy-a-function-in-google-cloud-45h8</link>
      <guid>https://dev.to/wrongbyte/how-to-deploy-a-function-in-google-cloud-45h8</guid>
      <description>&lt;p&gt;A cloud function is a single unit of code that can be executed in response to a specific event. In the context of serverless architecture, cloud functions are a way of deploying and running small pieces of code without the need for managing infrastructure. This can greatly simplify the process of building and deploying applications. So, let's learn how to deploy a simple function in Google Cloud Platform.&lt;/p&gt;

&lt;p&gt;Every function must have a trigger, which is the specific event that calls the function and makes our application "wake up". &lt;br&gt;
We can have event triggers or HTTP triggers, but I choose to use HTTP triggers for this tutorial.&lt;/p&gt;
&lt;h3&gt;
  
  
  How to do it, step by step
&lt;/h3&gt;

&lt;p&gt;First, you need to have Google SDK installed in your machine. Once you have it, authenticate to your account using&lt;/p&gt;

&lt;p&gt;&lt;code&gt;gcloud auth login&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Once you have this basic setup, let's start.&lt;/p&gt;
&lt;h3&gt;
  
  
  Writing a cloud function
&lt;/h3&gt;

&lt;p&gt;Let's use a javascript function here. I choose to use a &lt;strong&gt;HTTP trigger&lt;/strong&gt;. It means that &lt;strong&gt;our function will be triggered every time we receive a HTTP request to the URL assigned to it&lt;/strong&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;By default, Cloud Functions attempts to load source code from a file named index.js at the root of your function directory. To specify a different main source file, use the main field in your package.json file.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As we are dealing with HTTP triggers, we must create a simple function that runs every time we receive a request:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;myFunction&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;req&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;req&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;query&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;World&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;`Hello &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;!`&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="nx"&gt;module&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;exports&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;myFunction&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is our &lt;code&gt;index.js&lt;/code&gt;: nothing but a simple function. Our code here doesn't need to have a complicated structure, but it must have a &lt;strong&gt;function entry point&lt;/strong&gt;, which is the code that is executed when the Cloud Function is invoked.&lt;/p&gt;

&lt;h3&gt;
  
  
  Deploying
&lt;/h3&gt;

&lt;p&gt;In the code below,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;gcloud functions deploy &lt;span class="nv"&gt;$FN_NAME&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--entry-point&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nv"&gt;$FN_ENTRY_POINT&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--runtime&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;nodejs16 &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--region&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;us-central1 &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--trigger-http&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--allow-unauthenticated&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The important part is the &lt;code&gt;entry-point&lt;/code&gt; flag. It specifies &lt;strong&gt;which function&lt;/strong&gt; is the entry point. Google will lookup in our &lt;code&gt;index.js&lt;/code&gt; to find it.&lt;/p&gt;

&lt;p&gt;Another interesting flag is the &lt;code&gt;allow-unauthenticated&lt;/code&gt;. Without this flag, we would only be able to invoke our function if we made a request using a token from an account that has the &lt;code&gt;roles/cloudfunction.functions.invoker&lt;/code&gt; permission.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; to successfully use this flag, you need to have the &lt;code&gt;cloudfunctions.functions.setIamPolicy&lt;/code&gt; permission, since what &lt;code&gt;--allow-unauthenticated&lt;/code&gt; does is basically to set a IAM policy for your cloud function, enabling allUsers to invoke it.&lt;/p&gt;

&lt;p&gt;So, to deploy, we run &lt;code&gt;./deploy.sh&lt;/code&gt;. In the output of the commands, you'll se the URL that GCP assigned to your function.&lt;/p&gt;

&lt;p&gt;Go to it using your browser, and you'll be able to see "Hello World" printed in your screen.&lt;/p&gt;




&lt;p&gt;Still feel like you missed something? Take a look on the source code for this tutorial: &lt;a href="https://github.com/wrongbyte-lab/cf-tutorial" rel="noopener noreferrer"&gt;https://github.com/wrongbyte-lab/cf-tutorial&lt;/a&gt;&lt;/p&gt;

</description>
      <category>cryptocurrency</category>
      <category>blockchain</category>
      <category>web3</category>
      <category>crypto</category>
    </item>
    <item>
      <title>What I learned working for a big company</title>
      <dc:creator>wrongbyte</dc:creator>
      <pubDate>Thu, 17 Nov 2022 17:20:39 +0000</pubDate>
      <link>https://dev.to/wrongbyte/what-i-learned-working-for-a-big-company-part-1-3b3h</link>
      <guid>https://dev.to/wrongbyte/what-i-learned-working-for-a-big-company-part-1-3b3h</guid>
      <description>&lt;p&gt;There are undoubtedly many paths one can follow in their career as a programmer; and it's not about choosing &lt;em&gt;backend&lt;/em&gt;, &lt;em&gt;frontend&lt;/em&gt;, or an specific language to work with: it's about one's attitude and choices when it comes to development.&lt;br&gt;
However, often the environment in which you work has a lot of influence on which kind of dev you are going to become, as well as how long it will take for you to advance on your career. One of the decisive factors is the size of the company you work for.&lt;br&gt;
&lt;/p&gt;

&lt;h2&gt;
  
  
  Part 1: How a company shapes developers
&lt;/h2&gt;

&lt;p&gt;As said previously, the environment in which you spend a lot of time has a great influence over you and your work. &lt;strong&gt;Some companies place emphasis on skills that other companies undervalue&lt;/strong&gt;. This dynamic is responsible for shaping devs differently across different environments, and it is something important to understand because the more adaptable you are, the greater the chances to be successful in your career. &lt;/p&gt;

&lt;h3&gt;
  
  
  1- The generalist vs. the specialist
&lt;/h3&gt;

&lt;p&gt;I'm the kind of developer who likes to know how an application work, end-to-end - from the CSS to the choices for cloud providers. Although it's fun to do so in my personal projects, often it's not something possible to do in a big company.&lt;br&gt;
However, this is not &lt;em&gt;exactly&lt;/em&gt; a bad thing. As applications grow in size, it becomes more productive - for the devs and managers - to split responsibilities between scope-specific teams. It keeps them focused on a smaller scope, making it easier for new devs to get the context and quickly start to contribute to the codebase. &lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqcr5fp6qrjwsrzv8pogx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqcr5fp6qrjwsrzv8pogx.png" alt="illustrative image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It means less space for fullstack, generalist devs and more space for professionals who act on a more specific scope and are used to solve similar problems. In my last job I was the first fullstack on the team, which created some minor friction since this kind of role was something completely new in an environment where people worked in strictly defined scopes.&lt;/p&gt;

&lt;h3&gt;
  
  
  2- Soft and hard skills
&lt;/h3&gt;

&lt;p&gt;Before my first experience as a developer, I thought hard skills were the decisive factor when it comes to advancing quickly in seniority. Is it true? Well, it depends.&lt;br&gt;
Acting on a smaller scope means having a smaller surface under your/your team's responsibility. In practice, it implies  having different services under the responsibility of different people - and since many of these systems are interconnected, the people must be as well.&lt;br&gt;
It creates a contradiction - in theory, splitting responsibilities should increase teams' productivity and reduce coupling. But in practice, this is not always the case, because sometimes solving a cross-platform problem &lt;strong&gt;requires talking to a lot of different people&lt;/strong&gt;. You will have to roll up your sleeves and prepare to make all these people &lt;strong&gt;understand&lt;/strong&gt; your problem and &lt;strong&gt;look for a solution together&lt;/strong&gt;.&lt;br&gt;
Obviously, this will require much more than bare technical skills - it will demand from you a concise and effective communication. &lt;/p&gt;

&lt;p&gt;Therefore, the larger the company, the greater the need to evolve your skills beyond code and focus on making your communication effective and positioning yourself proactively.  This is the key to being a professional who makes a difference in this kind of extremely interconnected environment.&lt;/p&gt;

&lt;h3&gt;
  
  
  Sync and async work
&lt;/h3&gt;

&lt;p&gt;Sometimes calls cannot be emails.&lt;br&gt;
And sometimes you'll have to bet on sync communication to make things flow quicker, specially when there's no available documentation on sight.&lt;/p&gt;

&lt;p&gt;However, this is precisely the point where many managers fail - identifying when sync communication is &lt;em&gt;really&lt;/em&gt; necessary. So, you will have to be prepared for meetings, calls and sometimes unnecessary Scrum ceremonies. The greater the company, the greater the probability of this happening, because management teams tend to be more distanced from developers and thus have a distorted perception of which things are really important.&lt;/p&gt;

&lt;h3&gt;
  
  
  The lone programmer vs. the System Design Engineer
&lt;/h3&gt;

&lt;p&gt;I had a colleague who used to put a great emphasis on how "developers" are different from "architects/engineers". Although I disagree in parts, there are many contexts in which this analogy is true. Specially in the context of this post - &lt;em&gt;big companies.&lt;/em&gt;&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Developer&lt;/th&gt;
&lt;th&gt;Architect&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Knows all language-specific quirks&lt;/td&gt;
&lt;td&gt;Language-agnostic&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Focus on writing optimized code&lt;/td&gt;
&lt;td&gt;Focus on integrating systems&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Understand how things work under the hood&lt;/td&gt;
&lt;td&gt;Understand how things communicate&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Detail-oriented&lt;/td&gt;
&lt;td&gt;Big-picture thinker&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Can you be both? Yes, you can.&lt;br&gt;
But the environment in which you are usually tends to favor one type over another.&lt;br&gt;
Usually, more "structured" software will imply on less worries about details. This is often the path that corporations follow as they grow - &lt;strong&gt;they abstract things over time to gain productivity and reduce the required boilerplate to develop things&lt;/strong&gt;.&lt;br&gt;
You'll see it in the use of internal libraries or in the adoption of more opinionated frameworks; they reduce the quantity of micro technical decisions and favors the second type over the first one. But they also represent a very important downside of working in a big company: you'll have to take less important decisions.&lt;br&gt;
And it is very good for businesses, but sort of &lt;em&gt;bad&lt;/em&gt; for developers, specially if your desire is to learn as much as possible. You'll have less context under your hands and therefore, less opportunities to make mistakes and learn from them.&lt;br&gt;
&lt;/p&gt;


&lt;p&gt;Finally, it is important to keep in mind that the points listed above are not inflexible rules - rather, they are trends that I have personally been able to notice while working in and getting to know the environment of different companies.&lt;br&gt;
As a developer, the bottom line is to be as adaptable as possible within your context, and especially to have a sense of what to expect beyond the code in each of the companies you set out to work for.&lt;/p&gt;

</description>
      <category>career</category>
      <category>programming</category>
      <category>management</category>
    </item>
    <item>
      <title>What are closures?</title>
      <dc:creator>wrongbyte</dc:creator>
      <pubDate>Thu, 29 Sep 2022 23:57:17 +0000</pubDate>
      <link>https://dev.to/wrongbyte/what-are-closures-jm7</link>
      <guid>https://dev.to/wrongbyte/what-are-closures-jm7</guid>
      <description>&lt;p&gt;The concept of &lt;em&gt;closure&lt;/em&gt; is important when it comes to understanding how languages such as Javascript work - and how scopes, lifetimes and references come together and can be combined to provide useful features to programmers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Variables and their scopes
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1 - Local and global scope
&lt;/h3&gt;

&lt;p&gt;Every time you use a variable inside a function, this variable needs to be declared somewhere - and this place can be the &lt;strong&gt;local scope&lt;/strong&gt; (inside of the function) or the &lt;strong&gt;global scope&lt;/strong&gt;.&lt;br&gt;
Variables declared in the local scope are only accessible inside of their parent function - which means you cannot reference them outside of the function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// works&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;    
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// fails&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above, written in JS, we get an &lt;code&gt;Uncaught ReferenceError: a is not defined&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;However, by declaring &lt;code&gt;a&lt;/code&gt; as a global variable, we can reference it anywhere in our code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// works&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;    
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// works&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2 - Lifetime of entities
&lt;/h3&gt;

&lt;p&gt;The behavior above happens because entities (variables, constants, etc) have different &lt;strong&gt;lifetimes&lt;/strong&gt; across a program depending on their &lt;strong&gt;scope&lt;/strong&gt;. The definition of the "lifetime" of an entity can be thought as the period from its creation (allocating memory for it) to its destruction (deallocating the memory used for this variable).&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;global variable has the same lifetime of the entire program&lt;/strong&gt;. &lt;strong&gt;Local variables&lt;/strong&gt;, however, &lt;strong&gt;have specific lifetimes&lt;/strong&gt;, so they may not be "alive" during the entire program’s lifecycle. &lt;br&gt;
Hence, the underlying programming language must provide a way to deal which such cases, such as manual memory management or some kind of garbage collector. Otherwise, one could stumble upon a &lt;em&gt;dangling reference&lt;/em&gt; when not careful enough, since deallocated variables cannot be referenced.&lt;/p&gt;

&lt;p&gt;This dynamic is important to understand because we'll eventually get into a tricky question:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;What would happen if we wanted to reference a variable outside of its original scope?&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  3 - Nested functions
&lt;/h3&gt;

&lt;p&gt;There is a special use case of functions in which we face the question above.&lt;br&gt;
Let's say we wanted to create a function inside of another function. Let's call them &lt;code&gt;outer&lt;/code&gt; and &lt;code&gt;inner&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;outer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;inner&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
     &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;hello&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Everything declared inside of &lt;code&gt;inner&lt;/code&gt; has now access to the scope of &lt;code&gt;outer&lt;/code&gt;. &lt;br&gt;
It means that we can declare variables inside of &lt;code&gt;outer&lt;/code&gt; and then use them inside of &lt;code&gt;inner&lt;/code&gt;, as it follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;outer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;inner&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;inner&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;fnc&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;outer&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// execute outer to get inner &lt;/span&gt;
&lt;span class="nx"&gt;fnc&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can then return &lt;code&gt;inner&lt;/code&gt; from &lt;code&gt;outer&lt;/code&gt;. This part is important because it permits &lt;code&gt;inner&lt;/code&gt; to leave the scope of &lt;code&gt;outer&lt;/code&gt;.&lt;br&gt;
After that, we assign the return of outer to a variable &lt;code&gt;fnc&lt;/code&gt;, which we can execute to get &lt;code&gt;inner&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Therefore, we now have all variables of &lt;code&gt;inner&lt;/code&gt;, declared in &lt;code&gt;outer&lt;/code&gt;, &lt;em&gt;closed&lt;/em&gt; under this function. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What we'll seeing here is basically the implementation of &lt;em&gt;closures&lt;/em&gt; in Javascript: a function that has access to the additional data from its surrounding scope.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Therefore, we can define a closure as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1 - A function and
2 - A reference to that function's outer scope
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above, our &lt;u&gt;function&lt;/u&gt; is &lt;code&gt;inner&lt;/code&gt; and the &lt;u&gt;outer scope&lt;/u&gt; is the scope of &lt;code&gt;outer&lt;/code&gt;, which has the variable &lt;code&gt;a&lt;/code&gt;. Without keeping a reference to this surrounding scope, we would not be able to retrieve the value of &lt;code&gt;a&lt;/code&gt;. Once we have a reference to this surrounding scope, we have a closure.&lt;/p&gt;

&lt;h3&gt;
  
  
  Back to scope and lifetimes: what would happen if we didn't have closures?
&lt;/h3&gt;

&lt;p&gt;There are languages that don't implement closures. &lt;br&gt;
C is a good example: in C, you won't have closures as well as native support for nested functions. &lt;br&gt;
Using the simplified definition we've seen before, we can say that what's needed to implement closures is a record of the function along with its environment. &lt;br&gt;
To do this in C, there would be necessary to use structs, function pointers and a lot of fuzzy code. Furthermore, it would be necessary to have support for nested functions, which C doesn't have by default. Since closures are only meaningful when a function needs to be executed outside of the scope in which it was originally declared, having nested functions is essential for this concept to work.&lt;br&gt;
A lot of work, huh?&lt;/p&gt;
&lt;h3&gt;
  
  
  How Javascript solves it?
&lt;/h3&gt;

&lt;p&gt;We already learned that JS implements closures and what they are. But how does it work under the hood?&lt;/p&gt;

&lt;p&gt;Every function in JavaScript maintains a reference to its outer environment. This reference is used to determine the execution context of the function when it is invoked, and therefore enables the function to "see" variables declared outside of it.&lt;br&gt;
It creates a kind of &lt;em&gt;state&lt;/em&gt; particular to the functions declared in the same &lt;em&gt;lexical environment&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;💡 The lexical environment consists of any local variables in the function’s scope when the function is created.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In addition, if we have functions that call other functions that in turn call even more functions, JS creates a chain of references to the outer lexical environments - which is called the &lt;em&gt;scope chain.&lt;/em&gt; Therefore, closures in Javascript can become quite useful - and we are going to see a few uses for them now.&lt;/p&gt;
&lt;h2&gt;
  
  
  Why are closures useful?
&lt;/h2&gt;

&lt;p&gt;If you have ever programmed using an object-oriented language, you will probably know the concept of classes and states.&lt;br&gt;
Once you use a closure, you are creating the equivalent of a private state associated with a function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;foo&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;secret&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;Math&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;trunc&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;Math&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;random&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;inner&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;`The secret number is &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;secret&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;.`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;f&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;foo&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="c1"&gt;// &lt;/span&gt;
&lt;span class="nx"&gt;f&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above, &lt;code&gt;secret&lt;/code&gt; is not directly accessible from outside &lt;code&gt;foo&lt;/code&gt;. &lt;code&gt;foo&lt;/code&gt; then creates a kind of encapsulation similar to what we see in OOP, which is useful in several cases. Furthermore, JavaScript did not have a class syntax until 2015 - making the use of closures an alternative.&lt;/p&gt;

&lt;p&gt;Finally, there are several other use cases for closures - for example in functional programming, event-oriented programming and so on.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;💡 Further reading: &lt;a href="https://gist.github.com/wrongbyte/3b5f0b09706d818e24c5b18c4b2639cb"&gt;Nested functions, closures and first-class functions&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>javascript</category>
      <category>computerscience</category>
      <category>languagedesign</category>
    </item>
    <item>
      <title>Cryptography basics: breaking repeated-key XOR ciphertext</title>
      <dc:creator>wrongbyte</dc:creator>
      <pubDate>Tue, 05 Jul 2022 22:30:42 +0000</pubDate>
      <link>https://dev.to/wrongbyte/cryptography-basics-breaking-repeated-key-xor-ciphertext-1fm2</link>
      <guid>https://dev.to/wrongbyte/cryptography-basics-breaking-repeated-key-xor-ciphertext-1fm2</guid>
      <description>&lt;p&gt;In this post, we are going to learn a bit of what is the XOR encryption algorithm and how to decipher it through Friedman Test using Hamming Distance and Frequency Analysis.&lt;/p&gt;

&lt;h3&gt;
  
  
  First of all, what exactly is a XOR cipher?
&lt;/h3&gt;

&lt;p&gt;If you ever studied bitwise operators, you have already heard of &lt;em&gt;exclusive or&lt;/em&gt;, or simply XOR.&lt;br&gt;
It takes two inputs and returns 1 if these inputs are different.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj6iqp9pb4z712uc51ksc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj6iqp9pb4z712uc51ksc.png" alt="xor truth table"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;But the interesting part is that this simple operation, that happens in the bits level, is very useful for &lt;strong&gt;composing cryptographic keys.&lt;/strong&gt; That's what we'll see in this post, using a bit of Python and the problem presented in the 6th challenge of Cryptopals (set 1)&lt;/p&gt;

&lt;h3&gt;
  
  
  How can we use XOR as a method of encryption? In fact, what is a cryptographic cipher?
&lt;/h3&gt;

&lt;p&gt;To answer this question, let's think in terms of functions. Encrypting a message is taking its plaintext (or, more precisely, its &lt;em&gt;bytes&lt;/em&gt;), and generating an appearing random output with the help of an &lt;em&gt;encryption algorithm&lt;/em&gt;. &lt;strong&gt;This algorithm defines the pattern we'll follow when replacing the original content with the encrypted one.&lt;/strong&gt;&lt;br&gt;
For example, the Caesar cipher replaces a letter with its corresponding following letter, such that "ABC" becomes "BCD". This pattern goes through the whole message. &lt;br&gt;
But the Caesar cipher can skip more than one letter - what matters here is the logic of substitution. In this way, the &lt;strong&gt;XOR cipher is very similar.&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Bytes, ASCII and single-byte XOR
&lt;/h3&gt;

&lt;p&gt;Before introducing the encryption with a repeating cipher, let's first understand how a single-byte encryption would be done.&lt;br&gt;
The encryption with a single-byte XOR cipher is made when we use the XOR operation to change the value of each byte; we make this operation in the whole text using a key - that is the constant value which we are going to use to do this operation.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;

&lt;span class="n"&gt;binary_string&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sa"&gt;b&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;hello&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;byte&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;binary_string&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
   &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;byte&lt;/span&gt; &lt;span class="o"&gt;^&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The outputs will be &lt;code&gt;12, 1, 8, 8&lt;/code&gt; and &lt;code&gt;11&lt;/code&gt;.&lt;br&gt;
It happens because each letter in a binary string can be represented by a binary number that, XORed against 100 (the key here), returns a different byte. This number could be any value within the range [0, 255].&lt;br&gt;
Therefore, here &lt;code&gt;100&lt;/code&gt; acts as our key - we would need to know this value to perform the decryption of the message. &lt;strong&gt;Using a XOR cipher is a symmetric encryption method, what means that we need the same key both to encrypt and decrypt a message&lt;/strong&gt;. It happens because XOR is an involutory function - it's its own inverse, so to decrypt a message we would need to simply XOR its bytes against the key again.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frgl2ug8cbr2uzzsag85c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frgl2ug8cbr2uzzsag85c.png" alt="xor explained"&gt;&lt;/a&gt; &lt;br&gt;
So, we already have a substitution cipher similar in terms of Caesar cipher, &lt;em&gt;but a bit more sophisticated.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Side note 1:&lt;/strong&gt; it turns out that not all XORed bytes will be printable, since they can be outside the ASCII range. In this case, we can make a conversion to base64, for example, to print them. See &lt;a href="https://dev.to/wrongbyte/como-funciona-a-codificacao-em-base64-2njd"&gt;(in Portuguese)&lt;/a&gt;&lt;/em&gt;.&lt;br&gt;
&lt;em&gt;&lt;strong&gt;Side note 2:&lt;/strong&gt; the article above can also be helpful to help you understand how things work with ASCII characters in byte-level&lt;/em&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Repeating XOR cipher
&lt;/h3&gt;

&lt;p&gt;It turns out that encrypting something with a single-byte key would be a very weak encryption method. To break it, we would only need to know which key was used - which could be achieved by bruteforcing all the 256 possible values. Then, we could look at the outputs of these operations and choose the one that is more "English-like", by assign scores to each output, based on the most frequent letters across the English language.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PS: remember this function, we are going to see it later again!&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;

&lt;span class="c1"&gt;# Breaking a single-byte XOR cipher: we perform a XOR operation
# in the string using all possible values for the key.
# The key used to generate the output closer to English is what we are searching for.
&lt;/span&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;assign_score&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;output_string&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;string_score&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="n"&gt;freq&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt; &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;e&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;t&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;a&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;o&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;i&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;n&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;s&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;h&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;r&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;d&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;l&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;u&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;letter&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;output_string&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;letter&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;freq&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;string_score&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;string_score&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;XOR_decode_bytes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;encoded_array&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;last_score&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="n"&gt;greatest_score&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;256&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="c1"&gt;# checks for every possible value for XOR key
&lt;/span&gt;        &lt;span class="n"&gt;xord_str&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;byte&lt;/span&gt; &lt;span class="o"&gt;^&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;byte&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;encoded_array&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="n"&gt;xord_ascii&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;''&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="nf"&gt;chr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;xord_str&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
        &lt;span class="n"&gt;last_score&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;assign_score&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;xord_ascii&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nf"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;last_score&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;greatest_score&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="n"&gt;greatest_score&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;last_score&lt;/span&gt;
            &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;So, we can make it harder to break by simply creating a longer key - with more bytes and that repeats itself across the text.&lt;br&gt;
It would require us two steps to break: first, we would need to know the length of the key, and then we would need to know the key itself - which means testing each possible value for each one of the key's characters. A bit more complicated, right?&lt;/p&gt;

&lt;p&gt;So, let's understand how to encrypt a text using a XOR repeating key first.&lt;/p&gt;

&lt;h3&gt;
  
  
  Repeating key: encryption
&lt;/h3&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;

&lt;span class="n"&gt;input_text1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sa"&gt;b&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Burning &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;em, if you ain&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;t quick and nimble&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;I go crazy when I hear a cymbal&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
&lt;span class="n"&gt;XOR_key&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sa"&gt;b&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;ICE&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;XOR_repeating_encode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;input_string&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;bytes&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;bytes&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;bytes&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;xord_output&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;input_string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;input_string&lt;/span&gt;&lt;span class="p"&gt;)):&lt;/span&gt;
        &lt;span class="n"&gt;xord_output&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;input_string&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;^&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)])&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;bytes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;xord_output&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The logic here is pretty the same we used for the single-byte key. In short, we perform a XOR operation against each of the characters of the key, which is &lt;code&gt;ICE&lt;/code&gt; here. So, "B" is XORed against "I", "u" against "C" and "r" against "E", and so forth until we reach the end of the text. Getting the plaintext back is achieved through the same process.&lt;/p&gt;

&lt;h3&gt;
  
  
  But what if we wanted to recover the plaintext without knowing the key?
&lt;/h3&gt;

&lt;p&gt;Here things start to get interesting. Let's see how to break a repeated-key XOR ciphertext!&lt;/p&gt;

&lt;h3&gt;
  
  
  1 - The key's length: Hamming distance
&lt;/h3&gt;

&lt;p&gt;How far is "a" from "d"?&lt;br&gt;
You may say that they are a few letters apart in the alphabet. But there's another interesting way to measure their "distance": how many different bits they have - which is their &lt;strong&gt;Hamming distance&lt;/strong&gt;.&lt;br&gt;
So, lowercase a is 95 in the ASCII table, and lowercase d is 100. Their binary representations are &lt;code&gt;1011111&lt;/code&gt; and &lt;code&gt;1100100&lt;/code&gt;. They have 5 different bits, so &lt;strong&gt;their hamming distance is 5&lt;/strong&gt;.&lt;br&gt;
You can measure this distance across phrases, too - the process is the same, you only sum the result from each pair of characters.&lt;/p&gt;

&lt;h3&gt;
  
  
  What this measure has to do with the repeating XOR cipher?
&lt;/h3&gt;

&lt;p&gt;The average Hamming distance between two bytes picked at random is around &lt;code&gt;4.0&lt;/code&gt;, while that of any two lowercased ASCII alphabet - whose values range from 97 to 122 - is &lt;code&gt;2.5&lt;/code&gt;.&lt;br&gt;
So it means that the hamming distance between the characters of a plaintext will be much lower than that from a bunch of random bytes - and this information is very useful when we get to test the possible outputs for a variety of possible key lengths.&lt;/p&gt;

&lt;p&gt;Let's understand it better.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;hamming_distance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;string1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;bytes&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;string2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;bytes&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;distance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="nf"&gt;for &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;byte1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;byte2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;zip&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;string1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;string2&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;distance&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="nf"&gt;bin&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;byte1&lt;/span&gt; &lt;span class="o"&gt;^&lt;/span&gt; &lt;span class="n"&gt;byte2&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;count&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;1&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;distance&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Checking the different bits of two strings is basically the same as performing an XOR operation on them and counting the 1's, so the function above does exactly this. &lt;br&gt;
Alright. We now have a way to score a string to know the distance between its bytes. How can we use it now?&lt;/p&gt;

&lt;p&gt;In this challenge, the range of the size of possible keys is within the interval [2, 40]. Therefore, we will have to do the following steps:&lt;br&gt;
&lt;strong&gt;1) Divide our text into different chunk sizes, ranging from 2 to 40.&lt;br&gt;
2) On each iteration - for each chunk size chosen - we will check the hamming score between the chunks.&lt;br&gt;
3) The length of chunks with the lower average hamming distance corresponds to the key's length.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This technique works because, once we get the right size for the key, the chunks will be just XORed plaintext. Therefore, their hamming distance will be way lower than if they were random bytes. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;find_key_length&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
     &lt;span class="c1"&gt;# we are searching for the length that produces an output with the lowest hamming score
&lt;/span&gt;     &lt;span class="n"&gt;min_score&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

     &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;keysize&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;40&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;chunks&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;keysize&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="n"&gt;keysize&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
        &lt;span class="n"&gt;subgroup&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;chunks&lt;/span&gt;&lt;span class="p"&gt;[:&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="c1"&gt;# getting the average hamming distance per byte
&lt;/span&gt;        &lt;span class="n"&gt;average_score&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;hamming_distance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;combinations&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;subgroup&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;keysize&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;average_score&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;min_score&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;min_score&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;average_score&lt;/span&gt;
            &lt;span class="n"&gt;key_length&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;keysize&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;key_length&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the code above, the logic is as it follows:&lt;br&gt;
Let's say that we are guessing that the key is 4 characters long. If we had the following text:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;

&lt;span class="n"&gt;text&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;YWJjZGVmZ2hpamtsbW4=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We would divide it in several chunks with four letters each:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;

&lt;span class="n"&gt;chunks&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;YWJj&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;ZGVm&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;Z2hp&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;amts&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;bW4=&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, if we take the first four chunks, we are able to measure the average hamming distance between them:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;

&lt;span class="c1"&gt;# keysize here is equal to 4 and subgroup is the first four chunks
# dividing the score by 6 gives us the average diff between chunks, dividing it by keysize gives us the average diff between each a, b bytes for chunk1, chunk2
&lt;/span&gt;&lt;span class="n"&gt;average_score&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;hamming_distance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;combinations&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;subgroup&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;keysize&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  2 - The key itself
&lt;/h3&gt;

&lt;p&gt;Once we get the key's length, things get easier. &lt;br&gt;
In this particular challenge, it turns out that the key is 29 characters long. Even though we know the length, we still have 29 characters to guess, each one having 256 possibilities.&lt;/p&gt;

&lt;p&gt;How to do that? Well, the answer lies on matrices.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;find_key&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key_length&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;find_key_length&lt;/span&gt;&lt;span class="p"&gt;()):&lt;/span&gt; 
    &lt;span class="n"&gt;key_blocks&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;key_length&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="n"&gt;key_length&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
    &lt;span class="c1"&gt;# transpose the 2D matrix
&lt;/span&gt;    &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
    &lt;span class="n"&gt;single_XOR_blocks&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nf"&gt;list&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;filter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;None&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;zip_longest&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;key_blocks&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;block&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;single_XOR_blocks&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;key_n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;XOR_decode_bytes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;block&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key_n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="n"&gt;ascii_key&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;''&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="nf"&gt;chr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;ascii_key&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;encode&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If our key had exactly three characters - say the key was "RED" - then each first character of each chunk would be XORed against "R", the second against "E" and so on.&lt;br&gt;
So, if we joined each nth character of each chunk, the result would be a list of characters encrypted with a single byte XOR cipher, whose key is the nth character of our repeating key!&lt;/p&gt;

&lt;p&gt;Oof, that's too much. Let's see it in detail:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fputpgy2fh4t59m8syaa7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fputpgy2fh4t59m8syaa7.png" alt="cute"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The operation of creating an array joining every nth element of each chunk is basically transposing a matrix. &lt;br&gt;
To finally discover the key, then, we just need to apply the function that finds the key for a single-byte XOR ciphertext in each of the lines of our new generated matrix.&lt;br&gt;
And now, we have our deciphered plaintext! &lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fekoposymtd36shxw14z6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fekoposymtd36shxw14z6.png" alt="result"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can see the full code for this post &lt;a href="https://github.com/wrongbyte/study-stuff/blob/main/cryptopals/set1/6_break_repeatingXOR.py" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>cryptography</category>
      <category>python</category>
      <category>security</category>
    </item>
    <item>
      <title>Cracking a hashed password with hashcat</title>
      <dc:creator>wrongbyte</dc:creator>
      <pubDate>Thu, 16 Jun 2022 19:16:58 +0000</pubDate>
      <link>https://dev.to/wrongbyte/cracking-a-hashed-password-with-hashcat-4bfe</link>
      <guid>https://dev.to/wrongbyte/cracking-a-hashed-password-with-hashcat-4bfe</guid>
      <description>&lt;h3&gt;
  
  
  ... through a simple example of how this process works
&lt;/h3&gt;

&lt;p&gt;Given a hashed password &lt;code&gt;$2y$12$Dwt1BZj6pcyc3Dy1FWZ5ieeUznr71EeNkJkUlypTsgbX1H68wsRom&lt;/code&gt;, we have only one hint: &lt;strong&gt;the password has four letters, all lowercase.&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Let's start: finding the hash type
&lt;/h3&gt;

&lt;p&gt;There are &lt;strong&gt;a lot&lt;/strong&gt; of hashes out there. A good way to start guessing is to look at the hashed pass and try to find some kind of pattern. Here, the key is the first 4 characters of the hash.&lt;br&gt;
There is a page where you can look at example hashes: &lt;a href="https://hashcat.net/wiki/doku.php?id=example_hashes"&gt;https://hashcat.net/wiki/doku.php?id=example_hashes&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Noticed something?&lt;/strong&gt; We are looking for the &lt;em&gt;bcrypt $2*$, Blowfish (Unix)&lt;/em&gt;. Our &lt;code&gt;$2y$&lt;/code&gt; matches this pattern. So we are looking for a bcrypt hash. We also can grasp that the hash was generated using a factor of 12 (it is the number that comes after the first four characters).&lt;/p&gt;

&lt;h3&gt;
  
  
  Let's crack!
&lt;/h3&gt;

&lt;p&gt;First, it is important to know how the process works. Hashing is a process essentially different from encryption - you can only do it once. It means that we cannot &lt;em&gt;really&lt;/em&gt; recover the plaintext of a hashed password; instead, we can only compare its hash with our guesses. So, it's like hashing several words and seeing which of them matches exaclty our hash. Then, it must be the password.&lt;br&gt;
We can automatize this process with two tools: &lt;code&gt;hashcat&lt;/code&gt; and a dictionary of potential passwords. This kind of dictionary is easy to find on internet, so we are going to use &lt;a href="https://github.com/brannondorsey/naive-hashcat/releases/download/data/rockyou.txt"&gt;rock you&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Ok, so our dictionary is &lt;em&gt;very large&lt;/em&gt; and checking for each password, one by one, would be an expensive operation. But we already know how our password looks like, right? (four letters, all lowercase).&lt;br&gt;
So, let's filter our dictionary a little bit by creating a file containing all the passwords that match our condition: &lt;/p&gt;

&lt;p&gt;&lt;code&gt;grep -x -E '[a-z][^0-9]{4}' rockyou.txt &amp;gt; candidates.txt&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Here we are using &lt;code&gt;grep&lt;/code&gt; along with a regex expression to filter our potential passwords to only four-letters words without digits. The -x flag applies this expression to the whole line (our file contains one password per line), whereas the -E flag is needed because we are using an extended expression (due to the &lt;code&gt;{4}&lt;/code&gt; part).&lt;/p&gt;

&lt;p&gt;Now, we are ready to crack it with hashcat:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;hashcat -a 0 -m 3200 pass.txt candidates.txt --force&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Here, the code 3200 stands for the &lt;code&gt;bcrypt&lt;/code&gt; hash, and our hashed pass is stored in pass.txt whereas the potential passwords are stored in candidates.txt.&lt;/p&gt;

&lt;p&gt;After a few seconds (depending on your computer), we have the result:&lt;br&gt;
&lt;code&gt;$2y$12$Dwt1BZj6pcyc3Dy1FWZ5ieeUznr71EeNkJkUlypTsgbX1H68wsRom:bleh&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Where the "bleh" is the password we were looking for.&lt;/p&gt;

&lt;p&gt;&lt;del&gt;&lt;em&gt;In sum: use a password manager :)&lt;/em&gt;&lt;/del&gt;&lt;/p&gt;

</description>
      <category>security</category>
      <category>hacking</category>
    </item>
    <item>
      <title>How git stores your configs</title>
      <dc:creator>wrongbyte</dc:creator>
      <pubDate>Sun, 01 May 2022 19:08:00 +0000</pubDate>
      <link>https://dev.to/wrongbyte/do-you-know-how-git-stores-your-configs-3ekp</link>
      <guid>https://dev.to/wrongbyte/do-you-know-how-git-stores-your-configs-3ekp</guid>
      <description>&lt;h3&gt;
  
  
  How commits work?
&lt;/h3&gt;

&lt;p&gt;A commit contains information related not only to changes in files, but also to the committers in general. Github, for example, uses emails to link committers to their respective accounts in the platform.&lt;/p&gt;

&lt;p&gt;Therefore, working with git configs means directly changing the information associated with your commits.&lt;/p&gt;

&lt;h3&gt;
  
  
  Viewing your configs
&lt;/h3&gt;

&lt;p&gt;If you have ever had to change or view the name or email displayed in your commits, you probably know the &lt;code&gt;git config user.name&lt;/code&gt; command, or its variation &lt;code&gt;git config user.email&lt;/code&gt;. These commands are useful to check the information associated with your commits.&lt;/p&gt;

&lt;p&gt;But how git stores these configs &lt;em&gt;under the hood?&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Local and global configs
&lt;/h2&gt;

&lt;p&gt;Git stores configs in two different ways: globally or locally. Just like npm modules, the difference is where the files will be stored - inside of your current directory or in a system directory, being accessible from your whole system. &lt;strong&gt;This differentiation is useful when, for example, working with multiple git accounts on the same computer.&lt;/strong&gt; You will be able to configure which account you will be using for each repository.&lt;/p&gt;

&lt;h3&gt;
  
  
  Locally: the &lt;code&gt;.git&lt;/code&gt; directory
&lt;/h3&gt;

&lt;p&gt;Every time you start a git repository, what you are essentially doing is creating a .git directory inside it. You can open this file in VSCode by navigating to /.git (&lt;code&gt;cd .git&lt;/code&gt;) and typing &lt;code&gt;code .&lt;/code&gt;&lt;br&gt;
An empty repository will usually have a .git structure like this:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Fo5mHEIo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2qdhnudhqws5kofj5zvn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Fo5mHEIo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2qdhnudhqws5kofj5zvn.png" alt="git folder" width="189" height="181"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Every interactive git change you do in your repository - that opens a text editor, by default Vim on windows - is going to edit git files in this folder. For example, let's say we forgot to use the &lt;code&gt;-m&lt;/code&gt; flag when committing changes and it triggered a text editor to open:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--TRvdtTlU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hvkqvast73w8r3uy5a32.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--TRvdtTlU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hvkqvast73w8r3uy5a32.png" alt="vscode" width="585" height="215"&gt;&lt;/a&gt;&lt;br&gt;
 or, in Vim:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--C7F0c25---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zgsuxgx2gig9latpeubf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--C7F0c25---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zgsuxgx2gig9latpeubf.png" alt="vim" width="643" height="282"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In both cases, what you are doing is editing a file called &lt;em&gt;COMMIT_EDITMSG&lt;/em&gt; inside of your .git directory. &lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--vPG6Ea8x--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4harp6196xtdklqci4x2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vPG6Ea8x--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4harp6196xtdklqci4x2.png" alt="commit message" width="283" height="256"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It also happens when you use the &lt;code&gt;rebase -i&lt;/code&gt; command; in this case, you create a directory called &lt;em&gt;rebase-merge&lt;/em&gt;, that contains the file &lt;code&gt;git-rebase-todo&lt;/code&gt;, which is where you are going to make the changes.&lt;br&gt;
Git is also able to see if there's an ongoing rebase by checking if this directory exists or not:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--P_3vKml9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/say4murd353i9a1tndbd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--P_3vKml9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/say4murd353i9a1tndbd.png" alt="ongoing rebase" width="289" height="123"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--mCGJOSpi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q045es2apmadl5tqzdif.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--mCGJOSpi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q045es2apmadl5tqzdif.png" alt="git error" width="644" height="163"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Okay, but.. What does it have to do with configs?
&lt;/h3&gt;

&lt;p&gt;All of these stuff happens locally, inside of your repository. Naturally, the config file is also there, in a file named &lt;code&gt;config&lt;/code&gt; as well.&lt;/p&gt;

&lt;p&gt;If you open it, you'll be able to see a file like this:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--PPRwLGAs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jm4o6nvqy5vhfmb2ih2c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--PPRwLGAs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jm4o6nvqy5vhfmb2ih2c.png" alt="git config" width="435" height="249"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;These settings include the url of the remote repository, and some information about branches and merges.&lt;br&gt;
See, for example, what happens if we change the "origin" - the remote url - to something different, by changing its URL:&lt;br&gt;
&lt;code&gt;git remote set-url origin google.com&lt;/code&gt;&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--J16n5lp9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g252v177etxhszbb2ai3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--J16n5lp9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g252v177etxhszbb2ai3.png" alt="diff settings" width="455" height="270"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, our remote URL points to &lt;code&gt;google.com&lt;/code&gt; in the current repository.&lt;br&gt;
Commands such as &lt;code&gt;git remote set-url origin&lt;/code&gt; are shortcuts for editing the config file directly in your CLI. But these properties are not the only ones you can change; let's say that we have multiple github accounts and want to set which one we are going to use for commits in a particular repository.&lt;br&gt;
We can do so by adding, to our config file, the following properties:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--m71r6DFb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f5e94w05wiad7f98umrs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--m71r6DFb--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f5e94w05wiad7f98umrs.png" alt="change user etc" width="472" height="107"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;By doing so, we are overriding, for this repository, the &lt;em&gt;global git configs&lt;/em&gt;.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Side note: of course, using two github accounts on the same computer requires some additional steps, such as adding credentials to the Windows Credentials Manager, etc. But for customizing the author of commits, the method described here works.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Okay, but.. Where are the global git settings stored?
&lt;/h3&gt;

&lt;p&gt;Even though you want to change the committer's information for a repository, git has some default settings what will be shared with every new file tracked with git in your system. These are the global configs, and you can see them by typing &lt;code&gt;git config --list --global&lt;/code&gt;. &lt;del&gt;yeah, it also works with the --local flag&lt;/del&gt;&lt;br&gt;
Unlike the local configs, the global ones are stored inside of a file called &lt;code&gt;.gitconfig&lt;/code&gt;, that is inside of your system user directory. The changes applied to this file will have the same effect of setting things in the git CLI with a &lt;code&gt;--global&lt;/code&gt; flag.&lt;/p&gt;

&lt;h3&gt;
  
  
  In conclusion...
&lt;/h3&gt;

&lt;p&gt;Even though it's not very common to make changes in .git files directly (instead, you are probably going to use git bash), it may be useful to understand a bit of how things work under the hood. After all, git deals with your files by creating also some other files to track information. I encourage you to take a look not only at the &lt;code&gt;config&lt;/code&gt; file but also at other files and folders inside &lt;code&gt;.git&lt;/code&gt;, you may find interesting things there!&lt;/p&gt;

</description>
      <category>git</category>
    </item>
    <item>
      <title>The basic CSS guide for non-frontend developers</title>
      <dc:creator>wrongbyte</dc:creator>
      <pubDate>Thu, 24 Mar 2022 00:36:52 +0000</pubDate>
      <link>https://dev.to/wrongbyte/the-basic-css-guide-for-non-frontend-developers-1pij</link>
      <guid>https://dev.to/wrongbyte/the-basic-css-guide-for-non-frontend-developers-1pij</guid>
      <description>&lt;p&gt;&lt;strong&gt;This post is not intended to be a kind of cheat sheet; I'm not going to cover &lt;em&gt;every existing CSS property&lt;/em&gt;.&lt;/strong&gt; My intention here, on the other hand, is to present some useful CSS properties in a holistic way, showing how they can be used together and the logic behind them.&lt;/p&gt;

&lt;p&gt;I'm not a front-end developer though, so if something here seems a bit strange or confusing, I encourage you to look up on other resources. I hope this post is useful.&lt;/p&gt;

&lt;h3&gt;
  
  
  Box-model
&lt;/h3&gt;

&lt;p&gt;This one is the basics that you probably already know. &lt;br&gt;
Every single element in a page is nothing but a box containing these properties you see below:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faoa1pyiiz5gl11dz5n87.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faoa1pyiiz5gl11dz5n87.png" alt="box-model"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Although important&lt;/strong&gt;, I feel that most struggles people have have nothing to do with the box model itself, but with positioning &lt;strong&gt;each element in relation to each other.&lt;/strong&gt; So, I will skip box-model for now; even though we'll see a bit of it later.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Part 1 - Display: inline, block, inline-block
&lt;/h2&gt;

&lt;p&gt;We know that elements are built just like blocks in a page. However, are all elements equal when it comes to displaying them in your document? &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The answer is no&lt;/strong&gt;: they can be displayed occupying all the space around them or inside another block element, depending on the &lt;em&gt;default&lt;/em&gt; value of their &lt;code&gt;display&lt;/code&gt; property.&lt;/p&gt;

&lt;p&gt;Let's see.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw0un7deubl35ru51c5b0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw0un7deubl35ru51c5b0.png" alt="lorem ipsum p"&gt;&lt;/a&gt;&lt;br&gt;
Let's say we have a very basic &lt;code&gt;p&lt;/code&gt; tag containing some text. To write another paragraph, we would have to add another &lt;code&gt;p&lt;/code&gt; tag as follows:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3y3kr0k92nt4cynlttoe.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3y3kr0k92nt4cynlttoe.png" alt="two p"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;code&gt;display: block&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;By default, p is an element whose &lt;code&gt;display&lt;/code&gt; property is set to &lt;code&gt;block&lt;/code&gt;. The meaning of it is exactly what you saw above: &lt;strong&gt;block elements occupy all the width where they are positioned.&lt;/strong&gt; That's why we cannot have two p elements side-by-side, without changing their &lt;code&gt;display&lt;/code&gt; property.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;code&gt;display: inline&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;Let's say we've decided that our &lt;em&gt;lorem ipsum&lt;/em&gt; text looks boring without some colors. So, we need to change some stuff inside of p, which is a block element. How to do it?&lt;/p&gt;

&lt;p&gt;The answer is: &lt;code&gt;display: inline&lt;/code&gt;. Therefore, in this case, the best element we could use - that is &lt;code&gt;inline&lt;/code&gt; by default - is &lt;code&gt;&amp;lt;span&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6rm161orqjqavcldiqbo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6rm161orqjqavcldiqbo.png" alt="highlight"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Our HTML now looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight html"&gt;&lt;code&gt;&lt;span class="nt"&gt;&amp;lt;p&amp;gt;&lt;/span&gt;"&lt;span class="nt"&gt;&amp;lt;span&lt;/span&gt; &lt;span class="na"&gt;class=&lt;/span&gt;&lt;span class="s"&gt;"highlight"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;Lorem ipsum dolor sit amet&lt;span class="nt"&gt;&amp;lt;/span&amp;gt;&lt;/span&gt;
,consectetur adipiscing elit, sed do [...]&lt;span class="nt"&gt;&amp;lt;/p&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Basic differences between inline and block
&lt;/h3&gt;

&lt;p&gt;The width of your &lt;code&gt;block&lt;/code&gt; elements will not adjust to the content inside them; whereas it will happen with &lt;code&gt;inline&lt;/code&gt; elements.&lt;br&gt;
In fact, &lt;em&gt;"how to make my div adjust its width to the content inside"&lt;/em&gt; is a common question when it comes to CSS, and its answer is often setting the display property to &lt;code&gt;inline-block&lt;/code&gt; &lt;em&gt;(which will have characteristics of both &lt;code&gt;inline&lt;/code&gt; and &lt;code&gt;block&lt;/code&gt;)&lt;/em&gt;. Look at the answers of &lt;a href="https://stackoverflow.com/questions/450903/how-can-i-make-a-div-not-larger-than-its-contents" rel="noopener noreferrer"&gt;this question&lt;/a&gt; in Stack Overflow.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F67ebopec0j23p50nxrg7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F67ebopec0j23p50nxrg7.png" alt="diff inline-block and block"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Another difference that is worth noting is that block elements have top and bottom margins (remember the box model). That's visible in the image above.&lt;/p&gt;
&lt;h3&gt;
  
  
  But why do these differences even exist?
&lt;/h3&gt;

&lt;p&gt;A key concept to keep in mind is that &lt;em&gt;block&lt;/em&gt; elements are intended to be used as "wrappers" of sections in your page. That's precisely why elements such as &lt;strong&gt;&lt;code&gt;&amp;lt;main&amp;gt;, &amp;lt;header&amp;gt;, &amp;lt;article&amp;gt;, &amp;lt;footer&amp;gt;, &amp;lt;div&amp;gt;&lt;/code&gt;&lt;/strong&gt;, etc are block elements by default. They are supposed to have content inside them; therefore they start a new line and take up the full width available. &lt;em&gt;They are just like drawers&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;On the other hand, &lt;em&gt;&lt;code&gt;inline&lt;/code&gt; elements are like the items inside the drawer&lt;/em&gt;. Therefore, they occupy only as much width as necessary and are intended to be used inside block elements. It's easy to position they side-by-side.&lt;br&gt;
Some elements that are inline by default are &lt;strong&gt;&lt;code&gt;&amp;lt;a&amp;gt;, &amp;lt;button&amp;gt;, &amp;lt;textarea&amp;gt;, &amp;lt;label&amp;gt;, &amp;lt;select&amp;gt;&lt;/code&gt;&lt;/strong&gt;.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Farzdjum160ol2ss0xbep.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Farzdjum160ol2ss0xbep.png" alt="drawer analogy"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;br&gt;&lt;br&gt;
&lt;strong&gt;Side note: &lt;code&gt;grid&lt;/code&gt; and &lt;code&gt;flex&lt;/code&gt; are other important values for display, but we'll skip it for now, because a section of this post we'll be dedicated exclusively to grid and flexbox.&lt;/strong&gt;&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;p&gt;Let's add some colors to these paragraphs, first wrapping them in a div.&lt;/p&gt;
&lt;h3&gt;
  
  
  HTML
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight html"&gt;&lt;code&gt;      &lt;span class="nt"&gt;&amp;lt;div&lt;/span&gt; &lt;span class="na"&gt;class=&lt;/span&gt;&lt;span class="s"&gt;"wrapper"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;
          &lt;span class="nt"&gt;&amp;lt;div&lt;/span&gt; &lt;span class="na"&gt;class=&lt;/span&gt;&lt;span class="s"&gt;"yellow-div"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;p&amp;gt;&lt;/span&gt;"&lt;span class="nt"&gt;&amp;lt;span&lt;/span&gt; &lt;span class="na"&gt;class=&lt;/span&gt;&lt;span class="s"&gt;"highlight"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;Lorem ipsum dolor sit amet&lt;span class="nt"&gt;&amp;lt;/span&amp;gt;&lt;/span&gt;, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."&lt;span class="nt"&gt;&amp;lt;/p&amp;gt;&lt;/span&gt;
          &lt;span class="nt"&gt;&amp;lt;/div&amp;gt;&lt;/span&gt;

          &lt;span class="nt"&gt;&amp;lt;div&lt;/span&gt; &lt;span class="na"&gt;class=&lt;/span&gt;&lt;span class="s"&gt;"blue-div"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="nt"&gt;&amp;lt;p&amp;gt;&lt;/span&gt;"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."&lt;span class="nt"&gt;&amp;lt;/p&amp;gt;&lt;/span&gt;
          &lt;span class="nt"&gt;&amp;lt;/div&amp;gt;&lt;/span&gt;    
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  CSS
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight css"&gt;&lt;code&gt;&lt;span class="nc"&gt;.yellow-div&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nl"&gt;background-color&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="no"&gt;yellow&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nc"&gt;.blue-div&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nl"&gt;background-color&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="no"&gt;blue&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nc"&gt;.wrapper&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nl"&gt;width&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="m"&gt;800px&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Now our paragraphs look like this:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm3olac85kec1jsmr4wzz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm3olac85kec1jsmr4wzz.png" alt="800 pixels"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Our div now has a width of 800 pixels. But now we face our first problem: &lt;strong&gt;what if the width of our screen is less than 800 pixels&lt;/strong&gt;?&lt;/p&gt;


&lt;h2&gt;
  
  
  Part 2 - CSS Units
&lt;/h2&gt;

&lt;p&gt;If we wanted that our div had always &lt;em&gt;half the width of the page&lt;/em&gt;, it would be a headache to define its value in pixels. That's what would happen with our example: there are a lot of screens that are less than 800 pixels wide. But pixels are only the tip of the iceberg.&lt;/p&gt;
&lt;h3&gt;
  
  
  Relative lengths
&lt;/h3&gt;

&lt;p&gt;Pixels and centimeters are pretty self-explanatory. They are absolute, fixed length units and do not change in spite of other characteristics.&lt;br&gt;
However, due to their static nature, &lt;strong&gt;when dealing with responsive layouts, they are not always the best option.&lt;/strong&gt; That's why I will focus here on &lt;strong&gt;relative units&lt;/strong&gt;.&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;code&gt;em&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;em&lt;/code&gt; is equivalent to the font-size of parent div. It means that, for example, if the font-size of elements inside &lt;em&gt;yellow-div&lt;/em&gt; is set to 14px, then &lt;strong&gt;inside yellow-div&lt;/strong&gt;, 1em is equal to 14px, 1.2em is equal to 16.8px and so on.&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;code&gt;rem&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;This unit is similar to &lt;code&gt;em&lt;/code&gt;, but in this case we take for reference the font size of the root element (often &lt;code&gt;&amp;lt;html&amp;gt;&lt;/code&gt;). So, differently from the example above, we would not use the font-size of only yellow-div. If the font-size of the page is 18px, then 1rem would be equal to 18px &lt;strong&gt;in all elements of our HTML&lt;/strong&gt;.&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;code&gt;vh&lt;/code&gt; and &lt;code&gt;vw&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;These are my favorite units for responsive layout. &lt;code&gt;vh&lt;/code&gt; stands for viewport height and &lt;code&gt;vw&lt;/code&gt; stands for viewport width. They represent either 1% of width or height of page - &lt;strong&gt;and they resize accordingly to the viewport size&lt;/strong&gt;. That's very useful when you want, for example, a div that occupies half the page &lt;strong&gt;both in mobile and desktop screens&lt;/strong&gt;.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;p&gt;So, what about resizing our div to have 50% of the width of our page, despite of the screen size? Let's do it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight css"&gt;&lt;code&gt;&lt;span class="nc"&gt;.wrapper&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nl"&gt;width&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="m"&gt;50vw&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2qvzdbivitnrehn8cc3o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2qvzdbivitnrehn8cc3o.png" alt="50vw"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Look how the proportion is kept in smaller screens:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1kbjibztbb4h5ul4dd3l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1kbjibztbb4h5ul4dd3l.png" alt="50vw mobile"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;br&gt;&lt;br&gt;
Looks nice for now. But it could be better if our div was centered horizontally. How to do it?&lt;/p&gt;


&lt;h2&gt;
  
  
  Part 3 - centering stuff with CSS; an introduction
&lt;/h2&gt;

&lt;p&gt;We are back to the question that opened this post - &lt;em&gt;how to center a div?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The answer for this question varies a lot, actually. But we are going to start with the basics, first with two questions:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1 - Where is the element that you want to center?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2 - What's the nearest reference you are going to use to center it?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The first question is very important at this point, because out HTML has only a div with two paragraphs inside. It's different from a column in a blog template or some design alike. So, our element is floating alone in a HTML document and we are going to center it relative to our viewport.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;This case is not the most common; you are probably going to need to center your elements inside of other elements, and therefore the solution would be different. But for now, let's stick with it.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight css"&gt;&lt;code&gt;&lt;span class="nc"&gt;.wrapper&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nl"&gt;width&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="m"&gt;50vw&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nl"&gt;margin&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt; &lt;span class="nb"&gt;auto&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By simply adding &lt;code&gt;margin: 0 auto&lt;/code&gt;, we are able to center our div in this case.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpdjvuqcjh3pnit5ne5u5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpdjvuqcjh3pnit5ne5u5.png" alt="margin 0 auto"&gt;&lt;/a&gt;&lt;br&gt;
It is responsive as well:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq1a1jmqnogche3vw8uqf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq1a1jmqnogche3vw8uqf.png" alt="margin 0 auto mobile"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Back to box-model: why the solution above works
&lt;/h3&gt;

&lt;p&gt;Defining &lt;code&gt;margin: 0 auto&lt;/code&gt; does precisely two things: it sets the element's vertical margins to zero and lets the browser decide the horizontal margins - that will be equal in both sides. Of course, the values for the child element will be calculated relative to its parent element - and as we only have this div, the parent element is &lt;code&gt;&amp;lt;body&amp;gt;&lt;/code&gt; and so we are able to center it absolutelly.&lt;br&gt;
&lt;br&gt;&lt;br&gt;
However, using margins to center elements only works if:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1 - The element has a defined width&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2 - The element is &lt;code&gt;block&lt;/code&gt; (because we cannot define width for inline elements)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;So, as you see, this approach is useful - but only for very specific cases.&lt;br&gt;
&lt;br&gt;&lt;br&gt;
&lt;strong&gt;Side note: margin auto only works for centering things horizontally. It does not work on vertical axis the same way, look at the answers of &lt;a href="https://stackoverflow.com/questions/34552116/why-doesnt-margin-auto-center-an-element-vertically" rel="noopener noreferrer"&gt;this question&lt;/a&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;And so we get to another question: how to center stuff vertically, if we cannot use &lt;code&gt;margin&lt;/code&gt;?&lt;br&gt;
There are plenty of answers to this question. And to answer them, it's time to use another CSS property.&lt;/p&gt;


&lt;h2&gt;
  
  
  Part 4 - &lt;code&gt;position&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;Here things start to get interesting.&lt;br&gt;
In the previous example, let's say that we want to center our div vertically, taking for reference the browser window.&lt;/p&gt;

&lt;p&gt;Even though there are other ways to achieve it, we are going to use &lt;code&gt;position&lt;/code&gt; here.&lt;br&gt;
Let's start with the most useful cases: &lt;strong&gt;&lt;code&gt;absolute&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;relative&lt;/code&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;They set how the element should be positioned &lt;strong&gt;relative to&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1 - Its default position in the HTML document - &lt;code&gt;position: relative&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2 - Its parent element - &lt;code&gt;position: absolute&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt;
When you set position, you can define &lt;code&gt;top&lt;/code&gt;, &lt;code&gt;right&lt;/code&gt;, &lt;code&gt;bottom&lt;/code&gt; and &lt;code&gt;left&lt;/code&gt; properties, that will define the element's final position in the page layout.&lt;/p&gt;


&lt;h3&gt;
  
  
  What's the difference between them?
&lt;/h3&gt;

&lt;p&gt;In simple words, &lt;code&gt;absolute&lt;/code&gt; takes for reference the ancestor element and &lt;code&gt;relative&lt;/code&gt; takes for reference the &lt;em&gt;default position&lt;/em&gt; that the element would occupy in the page, if position is not set (normal flow). Look at the previous image and observe how elements are positioned. Relative will take for reference exactly these positions.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;code&gt;absolute&lt;/code&gt; is kinda tricky
&lt;/h3&gt;

&lt;p&gt;When we say &lt;em&gt;takes for reference the ancestor element&lt;/em&gt;, what &lt;strong&gt;exactly&lt;/strong&gt; it means?&lt;/p&gt;

&lt;p&gt;Basically, the reference for a absolute-positioned element is its &lt;strong&gt;nearest positioned element&lt;/strong&gt;, what is, &lt;strong&gt;the nearest element whose position is different from static (the default value).&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When we don't have this positioned element, though, the reference used will be the root element (&lt;code&gt;&amp;lt;html&amp;gt;&lt;/code&gt;). Let's see it in practice:&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;em&gt;Questionably&lt;/em&gt; centering with position
&lt;/h3&gt;

&lt;p&gt;So, we want our div to be centered vertically in terms of the browser window. If we use the root element for reference, &lt;code&gt;absolute&lt;/code&gt; would be the right choice, right? To test it, we are going to use the same logic of applying 50vh.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight css"&gt;&lt;code&gt;&lt;span class="nc"&gt;.wrapper&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nl"&gt;width&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="m"&gt;50vw&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nl"&gt;margin&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt; &lt;span class="nb"&gt;auto&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nl"&gt;position&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;absolute&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nl"&gt;bottom&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="m"&gt;50vh&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But look what happens:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftw25ml8orgyyokxxw4ne.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftw25ml8orgyyokxxw4ne.png" alt="position bug"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now our layout is broken because our element's margins are being ignored.&lt;/p&gt;

&lt;p&gt;In fact, &lt;em&gt;that's precisely what is intended to happen&lt;/em&gt;. When you use the absolute positioning, &lt;strong&gt;your element is removed from the document flow, what means that its &lt;em&gt;box is ignored&lt;/em&gt;.&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqrcgjd1mlv6hh2db8evv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqrcgjd1mlv6hh2db8evv.png" alt="outside window"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The margins are still there, but they have no effect now that our element is not part of the layout anymore.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;p&gt;But we still want our div to be part of the layout. So, let's use &lt;code&gt;position: relative&lt;/code&gt; instead.&lt;/p&gt;

&lt;p&gt;To do so, we can't use &lt;code&gt;50vh&lt;/code&gt; as our distance from the bottom, because now our reference is not the distance from the bottom of browser window anymore, but &lt;strong&gt;the default position of the element&lt;/strong&gt;. So, setting &lt;code&gt;bottom: 50vh&lt;/code&gt; with position relative would make our element disappear from the page.&lt;/p&gt;

&lt;p&gt;Then, we can use the distance from top to do it. &lt;em&gt;However, this distance certainly is not 50vh anymore.&lt;/em&gt;&lt;br&gt;
Why? Because &lt;strong&gt;it's not 50vh from top of page, but 50vh from where the element should normally be.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A way around this problem is to define the position value to &lt;code&gt;50vh - half the height&lt;/code&gt;. If the div has a height of 200px, our CSS now looks like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight css"&gt;&lt;code&gt;&lt;span class="nc"&gt;.wrapper&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nl"&gt;height&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="m"&gt;200px&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nl"&gt;width&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="m"&gt;50vw&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nl"&gt;margin&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt; &lt;span class="nb"&gt;auto&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nl"&gt;position&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;relative&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nl"&gt;top&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;calc&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="m"&gt;50vh&lt;/span&gt; &lt;span class="n"&gt;-&lt;/span&gt; &lt;span class="m"&gt;100px&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And our div is now vertically centered.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  An important property: &lt;code&gt;absolute&lt;/code&gt; inside &lt;code&gt;relative&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;It would be nice if we could position one element in terms of its parent div just like the drawer analogy, right? In fact, this is possible combining absolute and relative elements.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faoy8q2tdr81q86qsm00y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faoy8q2tdr81q86qsm00y.png" alt="absolute relative"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It happens exactly because &lt;code&gt;absolute&lt;/code&gt; (the yellow div, in this case) takes for reference the closest positioned element. And this element, here, is our &lt;code&gt;wrapper&lt;/code&gt; div.&lt;/p&gt;

&lt;p&gt;Look how we can define the properties above:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight css"&gt;&lt;code&gt;&lt;span class="nc"&gt;.yellow-div&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nl"&gt;position&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;absolute&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nl"&gt;right&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nl"&gt;height&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="m"&gt;100px&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nl"&gt;width&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="m"&gt;100px&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nl"&gt;background-color&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="no"&gt;yellow&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, &lt;code&gt;right: 0&lt;/code&gt; positions the yellow-div in terms of its parent div.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Important: there are other values for position. I will not cover them here, but I encourage you to research a bit about them.&lt;/strong&gt;&lt;/p&gt;



&lt;h2&gt;
  
  
  Part 5 - back to &lt;code&gt;display&lt;/code&gt;: flexbox and grid
&lt;/h2&gt;

&lt;p&gt;The first part of this post introduced &lt;code&gt;inline&lt;/code&gt; and &lt;code&gt;block&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now, it's time to see the &lt;em&gt;pinnacle of layout&lt;/em&gt;: flexbox and grid.&lt;br&gt;
&lt;br&gt;&lt;br&gt;
Flex and grid are &lt;code&gt;display&lt;/code&gt; values that, when applied to an element, allow you to organize the elements inside it as you want. You can organize them in rows, columns, or in personalized areas.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A little disclaimer: I will not describe their utilities in detail because it's probably out of the scope of this post; but I will list the recommended resources to learn each one.&lt;/strong&gt;&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Differences between them
&lt;/h3&gt;

&lt;p&gt;In most cases, their usage overlap and choosing between one or another is more of a personal choice.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;But observe the two layouts below:&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa5zitas2srkajvhfzg5i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa5zitas2srkajvhfzg5i.png" alt="different layouts"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;code&gt;grid&lt;/code&gt; - take a brick and divide it
&lt;/h3&gt;

&lt;p&gt;In the first layout, we have the content splitted in several sections. One example of it would be a blog page, where each section have a purpose - one of them may wrap the blog posts, another may show the recent posts, author information and so on. &lt;/p&gt;

&lt;p&gt;With grid, you can easily define what's called &lt;em&gt;grid areas&lt;/em&gt;. &lt;strong&gt;It makes &lt;code&gt;grid&lt;/code&gt; very powerful when you want to divide your content in independent, heterogeneous elements.&lt;/strong&gt; I like to think as grid being a way to divide your content in blocks and straightforwardly personalize their structure. Simply put, it's a method to draw a block and divide it in any way you want, by cutting it into lines.&lt;br&gt;
&lt;br&gt;&lt;br&gt;
&lt;strong&gt;To learn it in practice, play all the phases of &lt;a href="https://codingfantasy.com/games/css-grid-attack" rel="noopener noreferrer"&gt;this game&lt;/a&gt; and try to create/replicate a layout of your choice using what you understood.&lt;/strong&gt;&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;code&gt;flex&lt;/code&gt;- organize your items like on a shelf
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5auhnzfxcyi3g8di6h35.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5auhnzfxcyi3g8di6h35.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The second layout presents more homogeneous elements.&lt;/p&gt;

&lt;p&gt;The logic of flexbox is a bit different from grid: you can imagine the wrapper div with &lt;code&gt;display: flex&lt;/code&gt; being a shelf whose children elements are the items on it. &lt;/p&gt;

&lt;p&gt;For this reason, &lt;code&gt;flex&lt;/code&gt; is a good choice when you want to organize similar items - &lt;strong&gt;like the buttons in a navbar, the images of a gallery, homogeneous content in general&lt;/strong&gt;. Some properties of flex allow you to choose the order in which the items appear and if they are displayed in rows on in columns. &lt;code&gt;flex&lt;/code&gt; also presents the easiest way to center vertically and horizontally the contents of a div:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight css"&gt;&lt;code&gt;&lt;span class="nc"&gt;.random-div&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nl"&gt;display&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;flex&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nl"&gt;justify-content&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;center&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nl"&gt;align-items&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;center&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;To learn it, the strategy is the same as with grid, play &lt;a href="https://codingfantasy.com/games/flexboxadventure/play" rel="noopener noreferrer"&gt;this game instead&lt;/a&gt; and try to create/replicate a layout of your choice using what you understood.&lt;/strong&gt;&lt;/p&gt;



&lt;h3&gt;
  
  
  After all, how to master CSS?
&lt;/h3&gt;

&lt;p&gt;Personally, I believe that the only answer to this question is to create different front-end projects and &lt;strong&gt;practice&lt;/strong&gt;. Nowadays, it's rare to use pure CSS as you have bootstrap, tailwind and many other frameworks - for example, I used tailwind for &lt;a href="https://wrongbyte.vercel.app/" rel="noopener noreferrer"&gt;my blog&lt;/a&gt;!&lt;br&gt;
But using frameworks does not mean that knowing pure CSS is useless. After all, to decide which class to apply to an element, you first have to understand the document flow and what exactly you intend to do.&lt;/p&gt;

&lt;p&gt;Frameworks are just a way to prevent you from reinventing the wheel every single day, but they don't write the entire layout for you - you'll eventually need to fix the wheel when it breaks anyway.&lt;/p&gt;

</description>
      <category>css</category>
      <category>webdev</category>
      <category>frontend</category>
    </item>
    <item>
      <title>Como funciona a codificação em base64?</title>
      <dc:creator>wrongbyte</dc:creator>
      <pubDate>Wed, 23 Feb 2022 18:47:14 +0000</pubDate>
      <link>https://dev.to/wrongbyte/como-funciona-a-codificacao-em-base64-2njd</link>
      <guid>https://dev.to/wrongbyte/como-funciona-a-codificacao-em-base64-2njd</guid>
      <description>&lt;p&gt;Quando falamos de texto - ou, mais precisamente, as letras que compõem o alfabeto - estamos falando de caracteres individuais que são representados da mesma forma que números, quando lidos pelo computador. Isto é, tanto letras e números são convertidos para &lt;strong&gt;valores binários&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Veja a tabela abaixo:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fs2.glbimg.com%2FfEu3dqWDHAo0Gi1rGJin--DMiT4%3D%2F695x0%2Fs.glbimg.com%2Fpo%2Ftt2%2Ff%2Foriginal%2F2015%2F02%2F12%2Fimagem28.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fs2.glbimg.com%2FfEu3dqWDHAo0Gi1rGJin--DMiT4%3D%2F695x0%2Fs.glbimg.com%2Fpo%2Ftt2%2Ff%2Foriginal%2F2015%2F02%2F12%2Fimagem28.jpg" alt="tabela ascii"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Cada letra possui um índice na chamada tabela ASCII. Isso significa que podemos representar letras através de números.&lt;br&gt;
Logo, a palavra "Man" seria representada pelos valores 77, 97 e 110. &lt;br&gt;
Esses valores, por sua vez, convertidos para base binária, correspondem a &lt;code&gt;01001101&lt;/code&gt; &lt;code&gt;01100001&lt;/code&gt; &lt;code&gt;01101110&lt;/code&gt;.&lt;br&gt;
Até aqui, nenhuma informação muito nova. &lt;/p&gt;

&lt;p&gt;Contudo, o que acontece se quisermos codificar dados binários e transmiti-los através de locais que são designados para lidar com dados em texto (caracteres alfanuméricos)? &lt;br&gt;
A forma escolhida para fazer isso de maneira otimizada é &lt;strong&gt;codificar os dados na base64&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  O que é base64?
&lt;/h3&gt;

&lt;p&gt;Imagine que você quer inserir uma imagem em uma página web. Temos então um típico caso no qual a conversão para base64 é útil: páginas HTML são otimizadas para texto, e portanto converter as informações binárias para texto se torna interessante.&lt;/p&gt;

&lt;h3&gt;
  
  
  Como funciona a codificação?
&lt;/h3&gt;

&lt;p&gt;Para simplificar, vamos utilizar o exemplo anterior.&lt;br&gt;
A palavra "Man" é representada por 3 bytes, &lt;code&gt;01001101&lt;/code&gt; &lt;code&gt;01100001&lt;/code&gt; &lt;code&gt;01101110&lt;/code&gt;. &lt;br&gt;
Cada byte possui 8 bits, porém para iniciar a codificação para base64, precisamos que cada caractere corresponda a 6 bits. &lt;em&gt;(Detalhe: 2^6 é igual a 64, o número total de valores possíveis em base64, portanto o nome da codificação)&lt;/em&gt;&lt;br&gt;
Isso é feito juntando os 3 números, obtendo uma string de 24 bits: &lt;code&gt;010011010110000101101110&lt;/code&gt;.&lt;br&gt;
Dividindo a string de 24 bits em 4 dígitos de 6 bits cada, temos agora:&lt;br&gt;
&lt;code&gt;010011&lt;/code&gt; &lt;code&gt;010110&lt;/code&gt; &lt;code&gt;000101&lt;/code&gt; &lt;code&gt;101110&lt;/code&gt;, que correspondem, em decimal, a &lt;code&gt;19&lt;/code&gt;,&lt;code&gt;22&lt;/code&gt;,&lt;code&gt;5&lt;/code&gt; e &lt;code&gt;46&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;O próximo passo é encontrar a correspondência de cada dígito na tabela base64:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5i8q51ad7u1zer65zljs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5i8q51ad7u1zer65zljs.png" alt="tabela base64"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Finalmente, isso nos dá &lt;code&gt;TWFu&lt;/code&gt; como resultado. A codificação está feita. 🎉&lt;/p&gt;

&lt;h4&gt;
  
  
  A divisão em 24 bits e padding
&lt;/h4&gt;

&lt;p&gt;Sabendo que a conversão para base64 se dá em grupos de 24 bits, ou de 4 dígitos com 6 bits, chegamos a uma questão importante: &lt;strong&gt;o que ocorre caso não tenhamos os 4 dígitos completos?&lt;/strong&gt;&lt;br&gt;
Vamos supor que em vez de "Man", tenhamos "Ma". Isso resultaria em dois bytes, ou 16 bits no total.&lt;br&gt;
O próximo múltiplo de 6 é 18, logo, para que possamos ter 3 dígitos de 6 bits, precisamos adicionar 2 bits na string representada.&lt;br&gt;
Isso significa que &lt;code&gt;0100110101100001&lt;/code&gt; se torna &lt;code&gt;010011010110000100&lt;/code&gt;, porque adicionamos 2 bits - dois zeros - no final, o que é chamado de &lt;em&gt;padding&lt;/em&gt;. Assim, podemos então dividir essa string em 3 dígitos de 6 bits e adicionar um quarto bit para completar o quarteto. Esse bit é o padding que, na hora da conversão para ASCII, vai ser representado por &lt;code&gt;=&lt;/code&gt;. Então Ma corresponde agora a &lt;code&gt;TWE=&lt;/code&gt;.&lt;br&gt;
Veja, no exemplo abaixo, alguns casos onde o padding é adicionado:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fayqxq04qgkve5wcq7xzi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fayqxq04qgkve5wcq7xzi.png" alt="padding examples"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;É importante notar que nem sempre o padding vai ser obrigatório, já que é possível saber se há bits que faltam pelo tamanho da string codificada - já que esse número deve ser sempre múltiplo de 4.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
