<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yair Fernando on Medium]]></title>
        <description><![CDATA[Stories by Yair Fernando on Medium]]></description>
        <link>https://medium.com/@yairfernando?source=rss-5780cbfd325b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RyyNAe-8KRVc832N.jpg</url>
            <title>Stories by Yair Fernando on Medium</title>
            <link>https://medium.com/@yairfernando?source=rss-5780cbfd325b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:43:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yairfernando/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Go API — Database Connection]]></title>
            <link>https://yairfernando.medium.com/go-api-database-connection-d47e463cea37?source=rss-5780cbfd325b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d47e463cea37</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Yair Fernando]]></dc:creator>
            <pubDate>Sun, 27 Nov 2022 18:02:59 GMT</pubDate>
            <atom:updated>2022-11-30T22:44:24.666Z</atom:updated>
            <content:encoded><![CDATA[<h3>Go API — Database Connection</h3><p>Connect go api with PostgreSQL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRm68w-LQnfZU06uqPp76w.png" /></figure><p>In the previous article, we built the reverse proxy from the initial API design using gRPC and protocol buffers.</p><p>It’s time to connect our API to a database, we’ll use PostgreSQL this time.</p><p>If you missed the last article, I’d recommend reading the articles in the following order:</p><ol><li><a href="https://betterprogramming.pub/go-api-design-with-protocol-buffers-and-grpc-991838e4852b">Go API Design With Protocol Buffers and gRPC</a></li><li><a href="https://betterprogramming.pub/building-reverse-proxy-grpc-gateway-621696b29b0">Building Reverse Proxy (gRPC-Gateway)</a></li><li>Go API — Database Connection</li></ol><p>From the previous article we had the following folder structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*dbkLUimQznDZCPw6qMr1Bg.png" /></figure><p>We created a go module inside the proxy folder, now we’ll create another module for the API itself. In the root directory run the following command:</p><pre>go mod init github.com/yaairfernando/socialMedia</pre><p>This will create a go.mod file in the root directory of our project. We’ll come back to this file to add dependencies later. For now, let’s also create a main.go file which would be the API entry point.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22070cc5f0b9ac4c3a6af06b2aa082c9/href">https://medium.com/media/22070cc5f0b9ac4c3a6af06b2aa082c9/href</a></iframe><p>I like delegating tasks as much as possible from the main file, in this case, I am just calling the Run method on the server package, which we need to create next.</p><pre>mkdir server<br>cd server<br>touch server.go</pre><p>The server.go file is in charge to initialize the application and establish the database connection.</p><p>Before adding the logic to this file, let’s add two more services to the docker-compose.yaml file.</p><p>We need one service for our database and one more for the server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c33a322c9fd41580d0a9defc7f23b68c/href">https://medium.com/media/c33a322c9fd41580d0a9defc7f23b68c/href</a></iframe><p>For the postgres service, we’ll also need an init.sql file that will be run when the container starts. This file will contain the SQL to create the database.</p><p>The media service exposes port 8084 but runs internally on 8085, it also has some environment variables that we are passing, the DB_SQL_DATASOURCE which will be used to connect to the database, and the PORT which will be used later to initialize the server. It also specifies the docker file needed.</p><p>Let’s add the init.sql and the Dockerfile.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e10aa4ae25dc2586c20a79bcd48fd9dc/href">https://medium.com/media/e10aa4ae25dc2586c20a79bcd48fd9dc/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f900e35a12286bd67d30f007ab38d546/href">https://medium.com/media/f900e35a12286bd67d30f007ab38d546/href</a></iframe><p>As I mentioned the init.sql file only creates the database.</p><p>The docker file uses golang version 1.8 and also requires a GITHUB_ACCESS_TOKEN argument to download private repositories. Make sure this file is located under ./build/Dockerfile.</p><p>Now let’s add the logic to the server.go file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4a006b9e58461c8f96479d7e0b71e6e/href">https://medium.com/media/d4a006b9e58461c8f96479d7e0b71e6e/href</a></iframe><p>The initializeApp calls app.NewServer() which returns the server and an error, we’re not using the server at the moment.</p><p>We’re also getting the PORT environment variable that we’ll use later.</p><p>Let’s create another server file under theapp folder.</p><pre>mkdir app<br>cd app<br>touch server.go</pre><p>Let’s see how the server.go looks like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0659884cc434e1552e127934f3f7bf27/href">https://medium.com/media/0659884cc434e1552e127934f3f7bf27/href</a></iframe><p>This file represents the application’s server which will hold all database-related operations.</p><p>The Server struct has only one property Store of type store.Store. This is an interface that will include all the different DB stores the application handles. In this case the PostStore.</p><p>This file also delegates the initialization of the Store to a different package sqlstore.</p><p>Let’s add the store folder and files.</p><pre>mkdir store<br>cd store<br>touch store.go<br>mkdir sqlstore<br>touch store.go</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/010b0a5913765a2aeaa85846cd2a06ff/href">https://medium.com/media/010b0a5913765a2aeaa85846cd2a06ff/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd6bedc5a7c5b95f52b5d39d1d95d1e1/href">https://medium.com/media/fd6bedc5a7c5b95f52b5d39d1d95d1e1/href</a></iframe><p>This last file contains the logic to connect to the database. Let’s explore this file to see what is doing.</p><p>We have two structs, the SqlStore which has one property stores of type SqlStores, then the SqlStores struct has the different database stores available, in this case, we only have the store.PostStore, which is an empty interface at the moment.</p><p>The New function has the following logic:</p><ul><li>Initializes the SqlStore</li><li>Initializes the master database connection</li><li>Runs the database migrations</li><li>Returns the SQL store</li></ul><p>As we can see the SqlStore struct has two pointer receiver methods, one to implement the store.Store interface and one more to create the database master connection.</p><p>The initMasterConnection method calls another function to set up the database connection, sending master as the connection type and the dataSource which is retrieved from the environment variable in line 110.</p><p>The setupConnection function does the following:</p><ul><li>Opens a database instance using the driverName and dataSource.</li><li>Returns an error if the previous step failed.</li><li>Pings the database using the db instance.</li><li>Sets maximum open connections.</li><li>Returns the db instance.</li></ul><p>The function that pings the database connection has a really simple logic. It calls the PingContext method from the db instance using a context with a timeout. If that returns an error, it retries 10 times.</p><p>At this point, we have covered how to establish a database connection and ping it.</p><p>Let’s now see how to run migrations.</p><p>The runMigrations function does the following:</p><ul><li>Opens a database instance using the driverName and dataSource.</li><li>Returns an error if the previous step failed.</li><li>Uses the package golang-migrate to run all the migrations located under the folder db/migrations.</li></ul><p>We now have finished with the logic. Let’s download packages.</p><pre>go mod download<br>go mod tidy</pre><p>These are the dependencies needed in the go.mod file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/087646dbac6adf4610c9e66358bc541e/href">https://medium.com/media/087646dbac6adf4610c9e66358bc541e/href</a></iframe><h4>Migration to create Posts table</h4><p>If you already have installed the golang-migrate package we can use the CLI tool to create a new migration.</p><p>Before that make sure to create the db/migrations folder.</p><pre>mkdir db<br>cd db<br>mkdir migrations</pre><p>To create a new migration run this command:</p><pre>migrate create -ext sql -dir db/migrations -seq create_posts_table</pre><p>This will create two files in this directory</p><ul><li>000001_create_posts_table.up.sql</li><li>000001_create_posts_table.down.sql</li></ul><p>In these files, we need to add the SQL needed to create and drop the table.</p><p>The SQL to drop the table is pretty simple:</p><pre>DROP TABLE IF EXISTS posts;</pre><p>The SQL to create the table is the following:</p><pre>CREATE TABLE IF NOT EXISTS posts (<br>  Id SERIAL,<br>  Title varchar(128) NOT NULL,<br>  Description varchar(255) NOT NULL,<br>  Status integer NOT NULL,<br>  MediaIds integer[4],<br>  ScheduledAt bigint DEFAULT NULL,<br>  DeletedAt bigint DEFAULT NULL,<br>  CreatedAt bigint NOT NULL,<br>  UpdatedAt bigint NOT NULL,<br>  PRIMARY KEY (Id)<br>)</pre><p>With that the folder structure now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*S-pzpl4YoGnvvWF-e-FrbA.png" /></figure><h4>Running docker services</h4><p>We are now ready to run the docker-compose and see if the database connection was successful.</p><p>Let’s run the following command to build the services.</p><pre>docker-compose up --build</pre><p>You should see this in the console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e8CAvZihbsiA_aSk0vjarw.png" /></figure><p>As you can see we have the log Successful ping db connection which means the connection to the DB was correct.</p><p>We also see at the top of the image CREATE DATABASE which means that the init/sql file ran correctly as well.</p><p>Lastly, we did not get any errors regarding the migrations, which means they ran smoothly as well.</p><p>If we want to make sure that the migrations were applied correctly we can enter the postgres container and check.</p><p>To do that let’s follow these steps:</p><ul><li>Enter the container using bash: docker exec -it postgres bash</li><li>Access the console with the postgres user: psql -U postgres</li><li>List all the databases: \l+</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rFnGlMTEU90JlKD7MfjBxA.png" /><figcaption>List of databases</figcaption></figure><ul><li>Connect to a specific database: \c social_media_development</li><li>List all tables: \d+</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*VLytGxtsMRgTPjXz2c754w.png" /><figcaption>List of tables</figcaption></figure><ul><li>Select everything from the posts table: select * from posts</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*YpZONTxVFxWQQ-QIuNYVNg.png" /><figcaption>Posts table</figcaption></figure><p>As you can see the migration was applied correctly and the posts table was created.</p><h4>Key Takeaways</h4><ul><li>Added two more services to our docker-compose file, one for the database and one for the server.</li><li>Learned how to connect a postgres database with a golang application using docker.</li><li>Learned how to run migrations using golang-migrate</li><li>Learned how to inspect a docker container using docker exec</li><li>Successfully ping the database connection</li></ul><p>That is all for this article. In the next article, we’ll implement the server logic and the first API endpoint.</p><p>Stay tuned, and thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d47e463cea37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Reverse Proxy (gRPC-Gateway)]]></title>
            <link>https://medium.com/better-programming/building-reverse-proxy-grpc-gateway-621696b29b0?source=rss-5780cbfd325b------2</link>
            <guid isPermaLink="false">https://medium.com/p/621696b29b0</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Yair Fernando]]></dc:creator>
            <pubDate>Mon, 10 Oct 2022 20:28:21 GMT</pubDate>
            <atom:updated>2022-12-30T03:34:22.001Z</atom:updated>
            <content:encoded><![CDATA[<h4>gRPC API with protocol buffers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zh131FGzYbx8M19v4niZtQ.png" /><figcaption>combined image by author | right image by <a href="https://hub.docker.com/_/traefik">traefik</a>, left image by <a href="https://go.dev/src/net/http/httputil/reverseproxy.go">Go</a></figcaption></figure><p>In the last article, we built the API design for a social media application. We wrote the definition of five REST endpoints for a Post using Protocol Buffers as well as the HTTP annotations for each endpoint, we also generated the code to implement a reverse proxy using the <a href="https://github.com/grpc-ecosystem/grpc-gateway">grpc-gateway</a> plugin.</p><p>In this article, we’ll continue building the API and the next step is implementing the reverse proxy.</p><p>If you missed the last article, I’d recommend reading the articles in the following order:</p><ol><li><a href="https://betterprogramming.pub/go-api-design-with-protocol-buffers-and-grpc-991838e4852b">Go API Design With Protocol Buffers and gRPC</a></li><li>Building Reverse Proxy (gRPC-Gateway)</li><li><a href="https://yairfernando.medium.com/go-api-database-connection-d47e463cea37">Go API — Database Connection</a></li></ol><p>We’ll be using docker and docker-compose, so I recommend installing <a href="https://docs.docker.com/desktop/install/mac-install/">docker</a> and <a href="https://docs.docker.com/compose/install/#install-compose">docker-compose</a> first and make sure you are able to run containers.</p><p>Navigate to your GOPATH, if you don’t know what’s your go path directory, you can run echo $GOPATH and that will print the correct path. In there create the src/github/com/yaairfernando folder structure, replacing the last directory with your GitHub handle. Once you are there, create the following project structure:</p><pre>mkdir socialMedia<br>cd socialMedia<br>touch docker-compose.yaml</pre><p>All right, let’s start by defining the docker-compose yaml file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e7780b4c041c6b44945ae988c7ead14/href">https://medium.com/media/7e7780b4c041c6b44945ae988c7ead14/href</a></iframe><p>From the above yaml file, we are defining the proxy service, from the configuration of this service we can see that the container name is proxy, and the image that will use is sma:proxy, in case the docker image does not exist, it will build it from the ./proxy folder, we are also passing as arguments a GitHub access token, this is only necessary if you created a private repo for the API design from the previous article.</p><p>If so, you’ll need to pass a GitHub access token to the docker image to be able to access private repositories from the docker file.</p><p>We also specify a command and two environment variables to be run: one to specify the rest port where the server will be running, and a grpc URL, which points to the service that the proxy will be proxying requests.</p><p>We also specify that the port that this service will expose is 9094 and internally would be 8081.</p><p>Let’s now create a proxy folder and the main.go file:</p><pre>mkdir proxy<br>cd proxy<br>touch main.go</pre><p>Inside the proxy folder, we’ll run this command to create a go module</p><pre>go mod init github.com/yaairfernando/proxy</pre><p>This will create a go.mod file under the proxy folder.</p><pre>module github.com/yaairfernando/proxy</pre><pre>go 1.18</pre><p>The main.go file looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4347e25af214ad2bc3bd7c76aeafc545/href">https://medium.com/media/4347e25af214ad2bc3bd7c76aeafc545/href</a></iframe><p>The main function is only initializing a new server passing the grpcURL, restPort, and calling the start method on the server instance.</p><p>Let’s see what the server file looks like. Create the server folder and a server.go file.</p><pre>mkdir server<br>cd server<br>touch server.go</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4183bff8610e66811d95a59c6adf66b4/href">https://medium.com/media/4183bff8610e66811d95a59c6adf66b4/href</a></iframe><p>This server file has all the logic to register the handler for the Posts resource, add a simple logger, create an HTTP server and listen on the specified port.</p><ul><li>In line 36 we create a new server mux</li><li>In line 38, we wrapped that server with a simple logger</li><li>In line 40, we register all the handlers. In our case, we only have one for the Posts resource at the moment</li><li>Lastly, in lines 45–49 we create an HTTP server passing the handler and start listening</li></ul><p>As you can see, some helper functions are not defined in this file. I added them to a utils file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62a9b5e4a3788a77345dd11ed94b6b9c/href">https://medium.com/media/62a9b5e4a3788a77345dd11ed94b6b9c/href</a></iframe><p>All right, let’s now create the Dockerfile:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d3a7d40e75093083c9710a28c1d682f/href">https://medium.com/media/4d3a7d40e75093083c9710a28c1d682f/href</a></iframe><p>I will not go deep into what this docker file is doing, but essentially it uses a Golang image as the builder, sets some go environment variables, sets the working directory, and copies the go.mod file. After that, it downloads all dependencies, copies the rest of the files, and lastly, sets the entry point.</p><p>This is the go.mod file with all the packages that are used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8974e9ba7a9e54c9504b8a47c08c4dcf/href">https://medium.com/media/8974e9ba7a9e54c9504b8a47c08c4dcf/href</a></iframe><p>This is the final folder structure for the project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*qpD4reSx0g0jK87BBOlEUw.png" /></figure><p>We are almost done. Now, let’s download the go packages we need by running the following commands in the proxy folder:</p><pre>go mod download<br>go mod tidy</pre><p>As you can see for the sma package, we specified that we want version v0.1.0 from that package, but when we built the API design we did not create any versions. Let’s do that.</p><h4>Generate Git tag</h4><p>Go back to where you have the sma project, and let’s create a tag:</p><pre>git tag v0.1.0</pre><p>And push it to the repository:</p><pre>git push origin v0.1.0</pre><p>Now, back in the proxy folder, run this command to download that version of the sma package:</p><pre>go get github.com/yaairfernando/sma@v0.1.0</pre><p>The above command will download the sma package with the specified version.</p><p>One last thing before we build the service, add a .envfile with your GitHub access token in case your repo for the API design is private.</p><pre>GITHUB_ACCESS_TOKEN=your_gihub_access_token</pre><h3>Build Docker Service</h3><p>We can now build the proxy service by running the following command in the root folder:</p><pre>docker-compose up --build -d proxy</pre><p>When running this command you’ll get some errors saying to download some packages that we have specified in the go.mod file. Just download the packages by running go mod download package_path. And re-run the docker-compose command.</p><p>After the build finishes, we should be able to see the container running. Sending a POST request to <a href="http://localhost:9094/v1/posts">http://localhost:9094/v1/posts</a>will not work yet, but we can see the log.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*fhi8mjLei4D-vtzvyEpeCQ.png" /><figcaption>Proxy Running</figcaption></figure><p>That is all for this article. We have implemented the reverse proxy. In the next article, we’ll continue building the API.</p><p>Stay tuned, and thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=621696b29b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/building-reverse-proxy-grpc-gateway-621696b29b0">Building Reverse Proxy (gRPC-Gateway)</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Avoid Race Conditions in Golang]]></title>
            <link>https://medium.com/better-programming/how-to-avoid-race-conditions-in-golang-5e343146ed61?source=rss-5780cbfd325b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e343146ed61</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Yair Fernando]]></dc:creator>
            <pubDate>Mon, 13 Jun 2022 15:36:35 GMT</pubDate>
            <atom:updated>2022-08-27T02:55:34.927Z</atom:updated>
            <content:encoded><![CDATA[<h4>Write secure concurrent code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D_-zyLgVCyVctAWYrIAHhg.png" /><figcaption>image by author</figcaption></figure><p>One of the possible issues of implementing concurrent programs in Golang is data race conditions. This article will discuss this topic in detail and techniques used for identifying where race conditions can occur, strategies to prevent them and how Golang handles data shared between different concurrent contexts.</p><p>Before we start, if you are new to concurrency in Golang I’d highly recommend reading these articles first:</p><ul><li><a href="https://levelup.gitconnected.com/concurrency-in-golang-goroutines-and-channels-explained-55ddb5e1881">Concurrency in Golang, Goroutines, and Channels Explained</a></li><li><a href="https://betterprogramming.pub/file-processing-using-concurrency-with-golang-9e08920fab63">File Processing Using Concurrency With GoLang</a></li><li><a href="https://betterprogramming.pub/concurrency-with-select-goroutines-and-channels-9786e0c6be3c">Mastering Concurrency In Go — With Select, Goroutines, and Channels</a></li></ul><h3>What Is a Race Condition?</h3><p>Race conditions are the outcomes of two different concurrent contexts reading and writing to the same shared data at the same time, resulting in an unexpected output.</p><p>In Golang two concurrent goroutines that access the same variable concurrently will produce a data race in the program.</p><h4>Shared data</h4><p>It is common when running multiple goroutines, that data needs to be shared among them. If there is no safe strategy to access and modify data, this will result in a data race condition.</p><p>When writing concurrent programs, it is essential to identify all the variables that will be shared between goroutines.</p><h4>Critical sections</h4><p>A critical section is a block of code where a goroutine attempts to write a shared variable.</p><p>Every critical section in a concurrent program must implement a strategy to safely access and modify the shared data.</p><h4>Atomic operations</h4><p>Atomicity is a key concept when it comes to race conditions, shared data, and critical sections in a concurrent program.</p><p>We have talked about what is a race condition, how different goroutines shared data, what is a critical section, and that we need a strategy to safely access and modify data inside a critical section.</p><p>The strategy that a concurrent program needs to follow when accessing and modifying shared variables is to make sure that each operation that happens in a critical section is atomic.</p><p>An atomic operation ensures that no other process/context can read/write the shared data until the current process finishes the read/write operation. This means that a shared variable is atomic within the context where it is accessed/written. By having this characteristic in critical sections of a program, we can tell that the shared data is concurrency-safe. Thus race conditions will not happen.</p><p>Golang provides primitives for memory access synchronization so that operations can be atomic.</p><h3>sync.Mutex Package</h3><p>The sync.Mutex package provides a mechanism to guard a block of code, making it concurrency-safe, meaning write operations within that block will be safe. The primitives that the sync package provides allow you to write concurrent code using memory access synchronization to avoid data race conditions.</p><p>This mechanism constitutes using the Lock and Unlock, methods from the package.</p><p>The Lock method will establish that the goroutine who calls this method has just acquired the lock and no other goroutines can use the lock until it is released.</p><p>The Unlock method releases the lock so that other goroutines can use it.</p><p>When one goroutine is using the lock and another one tries to acquire the lock too, the goroutine will block until the other goroutine releases the lock.</p><p>Let’s see an example of a race condition and how we can solve it using a lock:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0fab44de63db0a3b31fd4da3727ea2d/href">https://medium.com/media/b0fab44de63db0a3b31fd4da3727ea2d/href</a></iframe><p>In the above scenario, two goroutines are appending to the slice of numbers. Let’s identify the shared data, critical sections, and race conditions.</p><p>In this example, it is obvious that the slice of numbers variable is the data that both goroutines are sharing, but it is still worth pointing it out because in a more complex program identifying what data is shared among several goroutines can be a challenge.</p><p>The critical sections on this example are the two append operations in lines 17 and 22, since we want these operations to be atomic in the context where they are run.</p><p>If we run the program, the following outcomes can be produced:</p><pre>// Expected<br>numbers &amp;[]<br>numbers &amp;[1 2]</pre><pre>// Expected<br>numbers &amp;[12]<br>numbers &amp;[12 1 2]</pre><pre>// Race condition<br>numbers &amp;[]<br>numbers &amp;[1]</pre><pre>// Race condition<br>numbers &amp;[]<br>numbers &amp;[12 1 2]</pre><p>As you can see the program does not guarantee that the output will be consistent and this is because two goroutines are running concurrently and modifying the same peace of data. Making it impossible to predict which operation will happen first. Thus causing a race condition.</p><p>To solve this problem the operations of appending numbers to the shared variable need to be atomic, the sync.Mutex can help us do that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d2f9eb3f95f0620e0f1aa09dc1cbc9e/href">https://medium.com/media/7d2f9eb3f95f0620e0f1aa09dc1cbc9e/href</a></iframe><p>Running the program will now produce only the two expected outputs:</p><pre>// Expected<br>numbers &amp;[]<br>numbers &amp;[1 2]</pre><pre>// Expected<br>numbers &amp;[12]<br>numbers &amp;[12 1 2]</pre><p>It is a common practice to call the mu.Lock() and then in a defer function the mu.UnLock() method, this is because a complex function where there are several possible ways of terminating the function either returning earlier or returning an error, using the defer function will make sure the lock is released when the function terminates, no matter which path it takes.</p><p>The sync package also provides another type of lock for only read operations. The sync.RWMutex provides the mu.RLock() and mu.RUnlock() methods to acquire and release the lock respectively. This is useful when there are scenarios where you want to lock a piece of code but the operations performed in that block are read-only.</p><h3>Conclusion</h3><p>Memory access synchronization primitives in Golang allow your program to lock and unlock operations so that they can run in a concurrency-safe manner. This ensures that a program that shares data among different goroutines runs correctly and avoids data race conditions.</p><p><em>Thank you for reading, and stay tuned for more.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e343146ed61" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-avoid-race-conditions-in-golang-5e343146ed61">How to Avoid Race Conditions in Golang</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang Type Assertion]]></title>
            <link>https://medium.com/better-programming/golang-type-assertion-d5517d81c366?source=rss-5780cbfd325b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5517d81c366</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Yair Fernando]]></dc:creator>
            <pubDate>Mon, 06 Jun 2022 15:25:45 GMT</pubDate>
            <atom:updated>2022-08-27T02:59:16.636Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using interfaces to determine behavior</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uKath8YtyN-1rFyR3Ttq6A.png" /><figcaption>Image by author</figcaption></figure><p>Golang provides a simple way of checking if an interface value is of a specific type. This is called type assertion, and it is generally used to make sure that an interface value satisfies another interface or to find the concrete type of the interface.</p><p>The syntax to assert if a value is of a specific type is represented below:</p><pre>var age interface{}<br>age = 20<br>str := age.(string)</pre><p>The variable age is of type interface{} which means it can hold any type. The concrete type that is assigned to the variable is int, but in this example, the type assertion is against the stringtype. The problem here is that the concrete type of the interface is not a string, and so running this program will produce a run-time error.</p><p>To remediate this, use what is called the “comma, ok” idiom, which would allow checking the type of the interface without producing an error.</p><pre>str, ok := age.(string)</pre><p>If the concrete type is not a string, the ok variable will be false, and the str variable will have the zero value of the type that was used to make the assertion. In this case, the zero value of a string is an empty string.</p><p>If the concrete type is a string, the ok variable will be true, and the str variable will have the value of the specified type.</p><p>Let’s look at a more elaborate example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e03346af23d1e2ea0dc42bed4e5595c5/href">https://medium.com/media/e03346af23d1e2ea0dc42bed4e5595c5/href</a></iframe><p>Here, the str variable is of type StringSelecter which is an interface that has two methods, String(), and Validate().</p><p>There is also a type called MyString and its concrete type is a string. This type has two value receiver methods, String(), and Validate(). This infers that this type satisfies the StringSelecter interface.</p><p>In line 12, the type of the str variable is printed.</p><p>The interesting part comes when the function typeAssert is called. This function takes an interface{} as its only parameter. The function needs to make sure that the concrete type of the value that is passed in as a parameter, satisfies the fmt.Stringer interface, that way it can safely call the String() method on the type.</p><p>To achieve this, it uses type assertion, using the “comma, ok” syntax. If the type assertion succeeds, the function calls the String() method on the value.</p><p>Running the above program will indeed output the print statement of line 19 since the parameter satisfies the fmt.Stringer interface.</p><p>What if the program also tries to call the Validate() method inside the typeAssert function, specifically after line 19. The following run-time error will occur:</p><pre>stringer.Validate undefined (type fmt.Stringer has no field or method Validate)</pre><p>Why is this? To understand this, let’s first see the difference between the two previous examples.</p><p>In the first example, the type assertion was against a concrete type string. In the second example, the type assertion was against an interface type.</p><p>Depending on the type that is used to make the assertion, the resulting value will vary.</p><p>If the assertion uses a concrete type, and the assertion succeeds, then the result would be the value of the variable that was asserted.</p><p>If the assertion uses an interface type, and the assertion succeeds, then the result would be the interface type that was asserted.</p><p>The previous example failed when calling the Validate() method because the assertion returned an interface type fmt.Stringer and that interface does not implement the Validate() method.</p><p>If the typeAssert function uses the StringSelecter interface instead, the resulting type would have the String() and Validate() methods accessible.</p><p>This characteristic of interface type assertion is heavily used to extend the set of methods that an interface value has, and also to determine the behavior of an interface value.</p><p>Let’s examine the copyBufferfunction from the Go source code that uses type assertion to determine which method to call to make the copy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64c0f7bba5a0787e40a9ce2c513e098f/href">https://medium.com/media/64c0f7bba5a0787e40a9ce2c513e098f/href</a></iframe><p>This function is used when using Copy from the io package.</p><pre>bytes, err := io.Copy(ioutil.Discard, resp.Body)</pre><p>The copyBuffer function above uses type assertion to determine which method can be used to do the copy operation. The WriteTo method is called to do the copy when the source satisfies the WriteTo interface. The ReadFrom method is called to do the copy when the source satisfies the ReaderFrom interface. Otherwise, it runs a different strategy to do the copy.</p><p>This is establishing behavior from the type interface Reader and assumes that if any of those two interfaces are satisfied by the src, then the WriteTo, and ReadFrom, methods are suitable to do the copy.</p><p>There is also another way of doing type assertion using a switch This article “<a href="https://levelup.gitconnected.com/switch-statement-in-golang-explained-9cd3a85aa19d">Switch Statement in Golang Explained</a>,” describes how!</p><p>If you are new to Golang, the following articles might be helpful:</p><p><a href="https://betterprogramming.pub/go-api-design-with-protocol-buffers-and-grpc-991838e4852b">Go API Design With Protocol Buffers and gRPC</a></p><p><em>I hope you enjoyed reading this article and learned something new. Feel free to share your valuable comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5517d81c366" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/golang-type-assertion-d5517d81c366">Golang Type Assertion</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Concurrency In Go — With Select, Goroutines, and Channels]]></title>
            <link>https://medium.com/better-programming/concurrency-with-select-goroutines-and-channels-9786e0c6be3c?source=rss-5780cbfd325b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9786e0c6be3c</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Yair Fernando]]></dc:creator>
            <pubDate>Fri, 03 Jun 2022 15:53:57 GMT</pubDate>
            <atom:updated>2022-08-27T03:06:37.749Z</atom:updated>
            <content:encoded><![CDATA[<h4>Write concurrent code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTexhywlIndISSifV3jwxg.png" /><figcaption>Image by author</figcaption></figure><p>In this article, we are going to talk about how to build concurrent programs combining select, goroutines, and channels in Golang.</p><p>I’d recommend reading these two articles first to get familiar with the concepts of concurrency, channels, and goroutines.</p><ul><li><a href="https://levelup.gitconnected.com/concurrency-in-golang-goroutines-and-channels-explained-55ddb5e1881">Concurrency in Golang, Goroutines, and Channels Explained</a></li><li><a href="https://betterprogramming.pub/file-processing-using-concurrency-with-golang-9e08920fab63">File Processing Using Concurrency With GoLang</a></li></ul><h3>Select</h3><p>From the Go tour documentation:</p><blockquote>“The select statement lets a goroutine wait on multiple communication operations.</blockquote><blockquote>A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.”</blockquote><h4>API Server Response</h4><p>We’re going to investigate how we can use select to take the response from the quickest API call. Let’s dive right into some code to understand select and its powerful features.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/872e9fdd78fe663043b11cf66c2b6bad/href">https://medium.com/media/872e9fdd78fe663043b11cf66c2b6bad/href</a></iframe><p>The above implementation focus on highlighting how a select will wait until one of its cases run.</p><p>Different parts are important to understand in this example, so let’s look at them one by one.</p><p>Before we look at the select logic, let’s examine how the API calls are made.</p><p>The Function struct represents a single API call, its attributes are a function f which takes a channel of type News, notice how the signature of this function already enforces that the channel will be treated as a send-only channel, the second attribute is a channel of type News, once the API call is executed, and the response is parsed, this channel will be used to send the results.</p><p>The Newsstruct is the object to hold the articles and from which source they come.</p><p>In line 43, we initialize a slice of Function, with two elements, the first one has the googleNews function and uses the google channel, and the second one uses the freeNews function and uses the free channel.</p><p>Since both API calls will fetch news, the channels are of the same type, but one for each function.</p><p>In lines 69 and 102, we have the implementations of these two APIs. Each one makes an HTTP request to their respective URLs and parses the response, once that is done, the news is sent through their respective channels.</p><p>Let’s now focus on quickestApiResponse method. The purpose of this method is to set the article variable to the response from the fastest API. In line 54, each function is executed by calling the Run method. This method starts a new goroutine on the function and passes the channel. It is important to note that these API calls need to run in a separate goroutine because we don’t want to run them sequentially.</p><p>Then, the select will wait for either the google or free channel to send a response. Once any of the API calls send the response through their respective channel, the select will execute the code under that case and ignore the other one. This will effectively set the articles to the response from the fastest API call.</p><p>Let’s run the program to see the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wBA2dNCXYt0k7S67zF6wXA.png" /><figcaption>API server response output</figcaption></figure><p>The FreeNewsApi ran faster!.</p><p>This logic can be applied to many other use cases, allowing the program to run multiple goroutines, use channels to communicate, and use select to wait for them.</p><p>One more thing we can implement in this example is to enforce some sort of time out, if the API calls take more than the limit we’ll just leave the articles empty. The code below achieves this by adding one more case to the select.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5867eddddf5be203d18237953823f8e/href">https://medium.com/media/f5867eddddf5be203d18237953823f8e/href</a></iframe><p>The time.After returns a channel of type time.Time, and it will send the current time once the time specified has passed. Notice how here we are not assigning the value of this channel to a variable, this is because we don’t care about the data that the channel will send, we only care about receiving the signal. If we sleep for three seconds on both APIs, we’ll see the time-out case being executed and the other two cases are ignored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*VhOzajVzHxGtbsAe1RYffA.png" /><figcaption>API server response timeout</figcaption></figure><h4>Context With Timeout</h4><p>Context is almost always present in a program, and we can use the context object to set a timeout for specific expensive tasks. The following example shows how to use context.WithTimeout to limit the time the program waits for a response of an expensive task.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca7702825659024f7b7318dc7ec8df18/href">https://medium.com/media/ca7702825659024f7b7318dc7ec8df18/href</a></iframe><p>The example above uses context.Background() as the parent context, but in a more realistic setting, the context will be present already. The context with timeout returns a context that will send a signal through the ctx.Done channel when the time duration specified has passed.</p><p>In line 13, an expensive task is run in a separate goroutine, the context and the signal channel are passed as parameters. The expensive task sleeps for 6 seconds to simulate latency, but the context has a time out of 5 seconds.</p><p>The select has two cases, waiting for either the ctx.Done to run or for the expensive task to send a signal indicating that it has finished.</p><p>In this case, running this example will result in the following output:</p><pre>Expensive task took too long to complete</pre><h4>Running Recurring Processes</h4><p>Let’s see how we can use selectto run a recurring process. For this program, we’ll have the following scenario:</p><p>The program needs to let us pass any function as the recurring process when that process should start running and an interval time between each run.</p><p>Below we have the initial code, let’s take a look:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc5b086579b10bd7e7d2fa61de3d7b2f/href">https://medium.com/media/fc5b086579b10bd7e7d2fa61de3d7b2f/href</a></iframe><p>The above code reflects the task that we want to run. We have two main functions collectNewUsersNotifications and handlePendingUsersNotifications. The first one is meant to collect all new user notifications, the ideal implementation would be that this function looks for unread notifications in a Database, but for the sake of this example, we are simulating getting random notifications for certain users.</p><p>The notifications are created using the Notification struct with only two fields one for the content and one for the user id.</p><p>The collect function uses the PendingUserNotifications type to store the notifications. This type is a map where the key is an integer representing the user id and the value is a slice of Notification.</p><p>After we collect all the notifications, we want to use handlePendingUserNotifications function to iterate over the notifications and run a handler function on each of them. After we process each user’s notifications, they are deleted from the map. The handler that we will use in this case is the sendUserBatchNotificationsEmail. Its purpose is to send an email to the user with all pending notifications so that they can take a look.</p><p>Let us focus now on how to run this task in a recurring fashion using select. As I previously mentioned we have to consider the following:</p><ul><li>Allow passing an interval time</li><li>Allow passing the start time of the process</li><li>Allow the caller to cancel/stop the recurring process when they want</li></ul><p>The below code shows how to achieve this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e03120ea532b765995935ae024d99877/href">https://medium.com/media/e03120ea532b765995935ae024d99877/href</a></iframe><p>We introduced a new struct to represent a recurring process RecurringProcess. This struct contains the following fields:</p><ul><li>name — The name of the process</li><li>interval — The interval time between each run</li><li>startTime — The time when the process will start</li><li>handler — A handler function to call on each run</li><li>stop — A channel to stop the process</li></ul><p>In pendingNotificationsProcess function, we initialize a new recurring process and the notifications in lines 30 and 31 respectively. The handler function that we will use is a function that has both collectNewUsersNotifications and handlePendingUsersNotifications functions inside. Notice here that we are passing the process to the handlePendingUsersNotifications because it will be needed to stop the process.</p><p>We also specified the interval and start time.</p><p>Then we call createRecurringProcess, this function creates the recurring process and starts it as well. Let’s focus on line 88, where we are using a goroutine to start the process.</p><p>In line 40, we block the main goroutine by reading from the stop channel, which means that the main goroutine will be blocked until a message is sent to this channel.</p><p>Let’s take a look at the Start function in line 93 which contains all the logic to run the recurring process.</p><p>This function uses the startTicker variable to start the recurring process using the start time. If the start time is in the past the process will start immediately.</p><p>The time.NewTimer will send the current time on its channel when the duration specified has passed, and this will allow us to start the process. This is why we have the first case of the select waiting for the channel to receive the signal.</p><p>We also have in line 95 a ticker variable which is a time.Ticker. A ticker in go will send ticks on its channel at the interval specified. Once the startTicker.C channel sends the signal, we assign a new ticker with the interval to the ticker variable in line 106 and also we call the handler function.</p><p>After this, the ticker will start receiving ticks on the second select case, and each time it receives one, the handler function will be called as well.</p><p>In the last case of the select, we wait until a signal is sent to stop the process by just returning.</p><p>Notice how the select is inside infinite for loop. This is because we want to keep looping until one of the cases explicitly breaks the loop. Each time we receive a tick, the second case will be executed and then it will enter in the same loop again where the select will again wait for some of its cases to run.</p><p>To stop the process we added some logic in line 55, we count the number of notifications and if there were no pending notifications at any point, the program cancels the process. The Cancel function closes the stop channel and this will make the program finish.</p><p>Let’s run the program to see how it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*oDBMDVhcAlfocQU4Y501Hg.png" /><figcaption>Program output</figcaption></figure><p>Great, the program works as expected. This is just an example of how to run a recurring process. This can be the base code to implement something more complex. You can build complex programs with select.</p><h4>Conclusion</h4><p>Building concurrent programs can be challenging at first, especially if you struggle to understand how goroutines, channels, and select work.</p><p>I hope with this article, you feel less confused, and you have found some use cases where you can use select.</p><p><em>Thank you for reading, and stay tuned for more.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9786e0c6be3c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/concurrency-with-select-goroutines-and-channels-9786e0c6be3c">Mastering Concurrency In Go — With Select, Goroutines, and Channels</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Switch Statement in Golang Explained]]></title>
            <link>https://levelup.gitconnected.com/switch-statement-in-golang-explained-9cd3a85aa19d?source=rss-5780cbfd325b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cd3a85aa19d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[enginerring]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Yair Fernando]]></dc:creator>
            <pubDate>Tue, 31 May 2022 12:15:57 GMT</pubDate>
            <atom:updated>2022-08-27T03:08:15.497Z</atom:updated>
            <content:encoded><![CDATA[<h4>With Practical Examples</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Bjg5V7zLT42HsodmuNEkw.png" /></figure><p>Golang like most programming languages has a switch statement. A switch allows you to evaluate a variable or expression against multiple cases and it is usually used when writing lots of if-else statements makes the code look ugly and repetitive.</p><p>Let’s take a look at an example to start seeing the different uses of the switch statement in Go.</p><pre>func variableEvaluation() {<br> name := &quot;John&quot;<br> switch name {<br> case &quot;John&quot;:<br>  fmt.Println(&quot;Hi it is John&quot;)<br> case &quot;Carl&quot;:<br>  fmt.Println(&quot;Hi it is Carl&quot;)<br> case &quot;Paul&quot;:<br>  fmt.Println(&quot;Hi it is Paul&quot;)<br> default:<br>  fmt.Println(&quot;Unkown name&quot;)<br> }<br>}</pre><p>For this first example, the switch evaluates the name variable, depending on the value it will print a different message. Notice how each case in the switch does not have a break keyword, this is because Golang by default breaks the switch when a case match. Also, there is a default option in case the variable does not match any of the cases in the switch.</p><p>A switch also allows you to put multiple values in a single case. This is useful when you want to perform the same operation in different cases.</p><pre>func statusEvaluation() {<br> status := &quot;active&quot;<br> switch status {<br> case &quot;active&quot;, &quot;inactive&quot;:<br>  fmt.Println(&quot;Update user&quot;)<br> case &quot;deleted&quot;:<br>  fmt.Println(&quot;Hard Delete user&quot;)<br> }<br>}</pre><p>We can also use expressions in a switch statement. Let’s see an example:</p><pre>func expressionEvaluation() {<br> num := 10<br> switch {<br> case num &gt; 10 &amp;&amp; num &lt; 20:<br>  num /= 2<br> case num &gt;= 20:<br>  num *= 2<br> case num &lt;= 10 &amp;&amp; num &gt; 0:<br>  num += 100<br> default:<br>  fmt.Println(&quot;Invalid number&quot;)<br> }<br> fmt.Println(&quot;Num: &quot;, num)<br>}</pre><p>In the above example the switch statement is not evaluating any variable, but rather each case has an expression, and if the expression matches the value of the variable that case will be executed.</p><p>We can also use the result of another function in a switch statement.</p><pre>func functionEvaluation() {<br> num := 12<br> switch b := isEven(num); {<br> case false:<br>  fmt.Printf(&quot;Num is odd %v %t\n&quot;, num, b)<br> case true &amp;&amp; num &lt; 5:<br>  fmt.Printf(&quot;Num is even %v %t\n&quot;, num, b)<br> case true &amp;&amp; num &gt; 10:<br>  fmt.Printf(&quot;Num is even %v, and greater than 10\n&quot;, num)<br> }<br>}</pre><pre>func isEven(n int) bool {<br> if n%2 == 0 {<br>  return true<br> }</pre><pre> return false<br>}</pre><p>In the above example, the switch is evaluating the result of the isEven function, and notice how we are defining the variable b in the switch statement, this is useful when we need the result of the function within the case.</p><p>We can also use a switch to know the type of a variable. This is useful when we have variables of type interface{}. Let’s see what this look like.</p><pre>func typeSwitch(elements interface{}) {<br> switch t := elements.(type) {<br> case int:<br>  fmt.Printf(&quot;Type integer %T\n&quot;, t)<br> case bool:<br>  fmt.Printf(&quot;Type boolean %T\n&quot;, t)<br> case []int:<br>  fmt.Printf(&quot;Type slice of integers %T\n&quot;, t)<br> case []string:<br>  fmt.Printf(&quot;Type slice of strings %T\n&quot;, t)<br> default:<br>  fmt.Println(&quot;Unkown type&quot;)<br> }<br>}</pre><p>As you can see from the previous code, the syntax to check the type of a variable using a switch is the same as for type assertion using the keyword type. We can also put multiple types in a single case if we want to perform the same operation.</p><p>Let’s run this example and see the output:</p><pre>typeSwitch([]int{1, 2, 3, 4, 5})<br>typeSwitch([]string{&quot;name&quot;, &quot;lastName&quot;})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*9mX8VLSg_SOJMs2GX2WliQ.png" /><figcaption>Type Switch Output</figcaption></figure><p>Let’s imagine that we have a function that takes a slice of bytes as a parameter, and we want to call this function, but the data that we have is of type interface{}, so before passing this data to the function we need to convert it to the right type. We can solve this problem using a type switch.</p><pre>func transformVariableToConcreateType(data interface{}) {<br> bytes := []byte{}</pre><pre> switch d := data.(type) {<br> case []byte:<br>  bytes = d<br> case string:<br>  bytes = []byte(d)<br> }</pre><pre> processData(bytes)<br>}</pre><pre>func processData(data []byte) {<br> fmt.Println(&quot;Processing data: &quot;, data)<br>}</pre><p>In this example, the type switch has two cases, one for a slice of bytes and one for a string. If the data is a slice of bytes it just assigns d to the variable bytes, if it is of type string, it converts it to a slice of bytes before assigning it to the bytes variable. After the switch statement transforms the data to the right type, it can now be passed to the processData function.</p><p>Let’s say that we have a function that takes a model, and this function is in charge of calling the right function to update the model based on which model it is. But since the update functions only accept pointers, the switch needs to handle this and pass the model as a pointer if it is not one already. We can also use a type switch to get the type of model and call the right function.</p><pre>func updateModel(model interface{}) {<br> switch t := model.(type) {<br> case *User:<br>  updateUser(t)<br> case User:<br>  updateUser(&amp;t)<br> case *Post:<br>  updatePost(t)<br> case Post:<br>  updatePost(&amp;t)<br> case *Chat:<br>  updateChat(t)<br> case Chat:<br>  updateChat(&amp;t)<br> }<br>}</pre><pre>func updateUser(user *User) {<br> fmt.Printf(&quot;Updating user %v\n&quot;, user.Name)<br>}</pre><pre>func updatePost(post *Post) {<br> fmt.Printf(&quot;Updating post %v\n&quot;, post.Title)<br>}</pre><pre>func updateChat(chat *Chat) {<br> fmt.Printf(&quot;Updating chat %v\n&quot;, chat.Participants)<br>}</pre><p>Here is the file with all examples we covered.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91b12b4b1a2604d85f712da86c63382c/href">https://medium.com/media/91b12b4b1a2604d85f712da86c63382c/href</a></iframe><h4>Conclusion</h4><p>The switch statement in Golang is pretty flexible and allows us to do several things and use it for different use cases. In this article we covered the following:</p><ul><li>Switch variable evaluation</li><li>Switch expression evaluation</li><li>Switch function evaluation</li><li>Type switch</li></ul><p>I hope you found this article useful and learned something new! Thank you for reading!</p><p><strong>Additional Readings</strong></p><ul><li><a href="https://levelup.gitconnected.com/concurrency-in-golang-goroutines-and-channels-explained-55ddb5e1881">Concurrency in Golang, Goroutines, and Channels Explained</a></li><li><a href="https://betterprogramming.pub/go-api-design-with-protocol-buffers-and-grpc-991838e4852b">Go API Design With Protocol Buffers and gRPC</a></li><li><a href="https://betterprogramming.pub/implementing-interfaces-with-golang-51a3b7f527b4">Implementing Interfaces With Golang</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cd3a85aa19d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/switch-statement-in-golang-explained-9cd3a85aa19d">Switch Statement in Golang Explained</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[File Processing Using Concurrency With GoLang]]></title>
            <link>https://medium.com/better-programming/file-processing-using-concurrency-with-golang-9e08920fab63?source=rss-5780cbfd325b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e08920fab63</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Yair Fernando]]></dc:creator>
            <pubDate>Mon, 30 May 2022 17:30:46 GMT</pubDate>
            <atom:updated>2022-08-27T03:13:11.995Z</atom:updated>
            <content:encoded><![CDATA[<h4>Master concurrency in Go</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hlz9v7VdJDf7O-bCz14vIw.png" /></figure><p>GoLang has incredible support for concurrent programs and in this article, we’ll see how we can optimize a program that processes a CSV file to send SMS notifications to its users.</p><p>If you’re new to using GoLang and want to get a better understanding of how concurrency works, I’d recommend reading this article first: <a href="https://levelup.gitconnected.com/concurrency-in-golang-goroutines-and-channels-explained-55ddb5e1881?gi=18f0db78ea33">Concurrency in GoLang, Goroutines, and Channels Explained</a>.</p><p>For this writing, we’ll be using a CSV file and the purpose of this program is to read the file and process its data. The file content represents a list of 3,000 users.</p><p>The program should read this file and send a notification to each user and their friends as well.</p><p>You can find the source code in this Github <a href="https://github.com/YairFernando67/fileProcessing">repository</a> for reference.</p><p>All right, let’s get started. We’ll first create a Go module, the main.go file, and a package called CSV. This package will have a method called ProcessFile which will be called from the main package. Let’s create the Go module first.</p><pre>go mod init github.com/GithubHandle/fileProcessing</pre><p>The initial folder structure looks as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*6iKdod5V29Oq7UCwejggRQ.png" /><figcaption>Folder Structure</figcaption></figure><p>As you can see there is also a students.csv file, you can grab this file from the repository. The main.goand the csv.go files look like this:</p><pre>package main</pre><pre>import &quot;github.com/YairFernando67/fileProcessing/csv&quot;</pre><pre>func main() {<br>  csv.ProcessFile()<br>}</pre><pre>package csv</pre><pre>func ProcessFile() {</pre><pre>}</pre><p>Now, let’s open the file and read its content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7862896e4d0dd4a033b4399db57c4b01/href">https://medium.com/media/7862896e4d0dd4a033b4399db57c4b01/href</a></iframe><p>In the above code, we’re first opening the csv file using the os package. Then the file is passed to another function called scanFile. This function uses the bufio package to initialize a new scanner and scan each line of the file. For each line, we extract the information about the user and append it to a slice of users. Once the scan finishes, the function returns the slice of users to the caller.</p><p>The user struct is defined in csv/user.go, and it looks like this.</p><pre>package csv</pre><pre>type User struct {<br>  Id, Name, LastName, Email, Phone string<br>  FriendIds                 []string<br>}</pre><p>If you run the program, you’ll see the slice of users being printed out to the console.</p><p>Sweet, we now have the content of the file represented as a slice of users, we can now use this slice to send an SMS notification to each of these users and their friends.</p><p>For that, we’ll first see how to do this sequentially, without using concurrency. Then we’ll modify the program to make it faster.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31f48528470b96940e6bbac5a472f870/href">https://medium.com/media/31f48528470b96940e6bbac5a472f870/href</a></iframe><p>For the sequential processing, we have created a function and passed the users into it. This function ranges over the users and for each user it checks if it has already been visited before, if it has not been visited, it marks the user as visited and sends the SMS notification. Then it also ranges over the user’s friend ids, find each user, and performs the same steps, checking if it has been visited or not, marking them as visited, and sending the notification.</p><p>In the sendSmsNotification function, we are using the time.Sleep function to simulate some latency in sending the notification.</p><p>Let’s run a benchmark test on this version of the program and see how fast it is. Here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/669a2ccf2fd2e225be1baa0228fc2266/href">https://medium.com/media/669a2ccf2fd2e225be1baa0228fc2266/href</a></iframe><p>Let’s run go test -bench=. github.com/yaairfernando/fileProcessing/csv -benchtime=5x</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*4ZfSlO2WC3i1OCOz9pjWnQ.png" /><figcaption>Sequential processing benchmark</figcaption></figure><p>It took 199.723seconds to process all users. Let’s see how we can improve the performance of the program using concurrency. For that, we’ll add another method to process the users concurrently.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51769d9d7a779d364463e506d607b899/href">https://medium.com/media/51769d9d7a779d364463e506d607b899/href</a></iframe><p>For this concurrent implementation, we have created two channels, usersCh will hold the initial list of users and unvisitedUsers will hold individual unvisited users.</p><p>In line 35, we are feeding the first channel with the initial list of users that we got as a parameter into this function. This runs in a separate goroutine, because we don’t want the main goroutine to be blocked, this is a concept that I talked about in this <a href="https://levelup.gitconnected.com/concurrency-in-golang-goroutines-and-channels-explained-55ddb5e1881">article</a>, you can go check it out if you’re still confused about the blocking concepts.</p><p>Then we call initializeWorkers. This function essentially initializes N number of goroutines determined by the constant MAX_GOROUTINES, in this case, we’ll start with 10. Each worker is a function that listens on the unvisitedUsers channel and for each user that it receives, it sends the SMS notification to the user and also processes its friend ids by finding each user in the list and then sending the users to the usersCh channel. The processing of the user’s friend ids is run in a separate goroutine since we don’t want to block the current goroutine here as well.</p><p>This function will allow the program to have 10 goroutines waiting for users to be sent to the unvisitedUsers channel. And each of these goroutines will run concurrently, thus improving the performance of the program.</p><p>Another important thing to note here is that in line 57 we are using this syntax to check if the usersCh channel is still open, this prevents us from sending data to a closed channel. In this example, this is important since we’ll be closing the channel and we don’t want other goroutines to attempt to send data to this channel.</p><p>Then in line 37, we have the processUsers function which ranges over the usersCh channel, and for each list of users that it receives, it checks if the user has already been visited, if not then it marks it as visited and sends the user to the unvisitedUsers channel. This function also keeps track of how many users have processed with the count variable, by doing this, we can check if we have reached the size in line 75 and close the usersCh channel which will terminate the program.</p><p>Let’s run the benchmark test for this version of the program and see how much it improved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*qldReCG0Y8W8Y0wGpL6h_g.png" /><figcaption>Concurrent processing benchmark</figcaption></figure><p>As you can see, it only took 19.936 seconds to finish!! This is a huge performance improvement. We can also control how many active goroutines/workers we want the program to have by increasing or decreasing the MAX_GOROUTINES constant.</p><p>If we increase the number of workers, our program will run faster since more tasks will be running concurrently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*ZFdSp3Sx_MOZqxldsCnc6Q.png" /></figure><p>This is a good example of how to improve the performance of a program using channels and goroutines. Channels are a great way of communication between goroutines, and goroutines allow you to run code concurrently.</p><p>I hope you found this writing useful and learned something new. Thank you for reading. Stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e08920fab63" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/file-processing-using-concurrency-with-golang-9e08920fab63">File Processing Using Concurrency With GoLang</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency in Golang, Goroutines, and Channels Explained]]></title>
            <link>https://levelup.gitconnected.com/concurrency-in-golang-goroutines-and-channels-explained-55ddb5e1881?source=rss-5780cbfd325b------2</link>
            <guid isPermaLink="false">https://medium.com/p/55ddb5e1881</guid>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Yair Fernando]]></dc:creator>
            <pubDate>Tue, 24 May 2022 11:24:49 GMT</pubDate>
            <atom:updated>2022-08-27T15:13:47.598Z</atom:updated>
            <content:encoded><![CDATA[<h4>Master concurrency in Go</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hlz9v7VdJDf7O-bCz14vIw.png" /></figure><p>Go is a powerful language because it handles several things effectively and efficiently, and one of those things that make it fascinating and powerful is how it handles concurrency.</p><p>In this article, I’ll aim to explain fully the core concepts of concurrency, and the approach that Golang follows to accomplish concurrent programs.</p><h4><strong>Let’s start by defining what is concurrency:</strong></h4><p>A program is considered concurrent if it can deal with multiple tasks at the same time. The concept of concurrency involves the ability of a program to run several operations concurrently, even when this does not necessarily mean that these operations are running explicitly at the same time, each task can start at a different point in time. Let’s see a diagram to better grasp what concurrent operations would look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*juuQ-GGhJ4iXAUW8NWzt6Q.png" /></figure><p>These operations might not start at the same time, but they are running concurrently with each other. This means that a task does not have to wait until another task finish before running.</p><p>On the other hand, if your program runs multiple operations at the same time, meaning they start exactly at the same point in time, that would be considered parallelism. When using concurrency your program can also achieve parallelism, depending on the use cases.</p><h4>Golang concurrency model</h4><p>Golang approaches concurrency using <strong>goroutines. </strong>A<strong> </strong>goroutine is managed by the Go runtime and is pretty similar to a thread, but with several advantages. Goroutines allow you to run multiple operations concurrently. In a multithreaded environment, to run various operations concurrently a new thread has to be created by the OS, which involves a considerable amount of resources, memory, and time, so running multiple operations concurrently using threads is more expensive for the OS. On the other hand, a goroutine is lightweight, efficient and it does not cost too many resources to be created, spinning up several hundreds of goroutines is not a problem in Go.</p><h4>Shared resources with goroutines</h4><p>When running multiple goroutines to complete different tasks, very often than not you’ll find that goroutines need to access and modify shared resources, if multiple goroutines are accessing and modifying the same data at the same time this will lead to several problems, unexpected results and what is called race conditions.</p><p>Let’s define what is a race condition in the context of a concurrent program.</p><p>A race condition occurs when multiple operations running concurrently attempt to read/write the same data at the same time.</p><p>To avoid this situation golang uses locks so that only one goroutine can modify a certain piece of data at a time. This is a really important topic<br>since a key component when implementing concurrency is ensuring that your program will not end up with unexpected results.</p><p>For now, let’s write our first concurrent program and see how to create a goroutine using the go keyword:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7aa426aa479de5c56ef0dc5b51ff5f62/href">https://medium.com/media/7aa426aa479de5c56ef0dc5b51ff5f62/href</a></iframe><p>In this example, we have the main function which is only printing a message in line 6, when the program runs it creates what’s called the main goroutine, this goroutine is created automatically when running your program and it is where all your code is executed, but if you want to run another operation in a separate goroutine, we can use the <strong>go</strong> keyword before the function we want to run concurrently and that will effectively create a new goroutine and run that function.</p><p>In line 8 we are telling the program to create a new goroutine for the <strong>countNumbers</strong> function. Then going back to the main goroutine, in line 10 there is another print statement.</p><p>So, why don’t we see the print statement that is inside the <strong>countNumbers</strong> function?. Well, it is because the main goroutine does not wait for other goroutines to finish their work, the main goroutine will continue the execution of the main program and it will terminate without waiting to see if other goroutines have finished.</p><p>To allow the <strong>countNumbers</strong> function to finishing we can sleep 1 second in the main go routine in line 9.</p><pre>time.Sleep(1 * time.Second)</pre><p>If you run the program again you’ll see the print statement now, this solution is not ideal in any concurrent program, so we’ll see later how to accomplish this using channels.</p><h4><strong>What is a channel?</strong></h4><p>A channel is a way of communication between different goroutines. It is a safe way of sending values of one data type to another goroutine. A channel is passed by reference meaning that when creating a channel and then passing it to other functions, these functions will have the same reference pointing to the same channel. If you understand how pointers work, this might be simple to understand with channels.</p><p>We can compare channels only if they have the same type and as I previously mentioned since they are passed by reference, a comparison between two channels will evaluate true if both are pointing to the same reference in memory. We can also compare a channel with nil.</p><p>The purpose of a channel is to allow goroutines to send and receive information, but frequently they are also used to inform other goroutines<br>that a process has finished and not necessarily sending any information through the channel.</p><p>A channel can also be closed, meaning it will no longer accept any more messages to be sent or received and if a goroutine tries to send or receive a message from a closed channel the program will panic, unless we use a special syntax to read from the channel or we use the a range loop. We’ll see in a moment how this works.</p><h4><strong>Type of channels</strong></h4><p><strong>Unbuffered Channels:</strong> This type of channel only allows to send one piece of data and blocks the current goroutine until another one performs a receive operation on the channel. The same thing will happen if a receive operation on a channel is performed before a send operation, the goroutine where the receive operation was made will be blocked until another goroutine sends a message through the same channel.</p><p>To demonstrate this blocking concept when using unbuffered channels, let’s see the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da009fb78d9b7ffb8ff36a27a1fd0f0c/href">https://medium.com/media/da009fb78d9b7ffb8ff36a27a1fd0f0c/href</a></iframe><p>Running the previous example will output the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*LtwfPSwiQM5EB4lM9mSfBg.png" /></figure><p>Let’s understand the output. When the program starts, an empty user object is created and a channel of type boolean(unbuffered channel) in lines 36 and 37 respectively, then a goroutine is created in line 39 which means that the piece of code within that function will be running in a separate goroutine.</p><p>The execution of the main goroutine continues and in line 49 we have a print statement, then in the second goroutine, since it is running concurrently at this point, it reaches line 40 and also executes a print statement.</p><p>The main goroutine continues and calls the method <strong>importingPosts</strong> and makes also two more print statements, the last one being [Main-Goroutine] — — -waiting------ , this is where the blocking concept that we talked about earlier comes into play, in line 53 we see that the main goroutine is reading from the donechannel, this basically means that the main goroutine will not continue its execution until the second goroutine sends a message to this channel.</p><p>In the second goroutine, the <strong>buildUser</strong> function is called and it prints [Second-GoRoutine] Finished Building User , then in the next line, it sends a message to the channel. At this point, the main goroutine will detect this and it will continue its execution, as well as the second goroutine.</p><p>The methods <strong>mergeUserPosts</strong> and <strong>setDefaultTags</strong> are called in the main and second goroutine respectively and we get their corresponding logs.</p><p>When we get to lines 57 to 60, the user and its posts are printed out, but if you check the tags array in the user struct is empty. The reason is that after the second goroutine sent a message to the main goroutine, both goroutines continued executing concurrently and as I previously mention the main goroutine will not wait until other goroutines finished executing, that being said, the second goroutine did not complete its work appending the user tags into the struct before the main goroutine finished and that is why the array is empty. If we remove line 91, we’ll be able to see the tags array is now filled in.</p><p>With this example, we learned how to create an unbuffered channel using the built-in make function.</p><pre>done := make(chan int)</pre><p>Also how to send and receive data from a channel</p><pre>done &lt;- true // send<br>&lt;-done // receive ignorting value<br>resp := &lt;-done // receive storing value in a variable</pre><p>Also, we saw how goroutines block execution if no other goroutine has sent/receive a message through the channel.</p><p>Channels are also used as a way of connecting multiple goroutines by using the result of one goroutine as the parameters for another one.</p><p>Let’s take a look a the next example this time using multiple goroutines.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61b938e2564556d4f9674c6c3fc0cb66/href">https://medium.com/media/61b938e2564556d4f9674c6c3fc0cb66/href</a></iframe><p>The output of this example looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*NbFu2F_nmn0IUO-LlxGp-w.png" /></figure><p>In this example, we have two channels <strong>usersToUpdate</strong> and <strong>userToNotify</strong>, notice how the first channel accepts an array of users and the second one only one single user object. Then there are two arrays of users, one for existing users and one for new users.</p><p>In the first goroutine, we send the <strong>usersToUpdate </strong>channel<strong> </strong>and the slice of <strong>newUsers</strong>, so when the program gets to line 40 a new goroutine is created.</p><p>Notice the syntax in <strong>filterNewUsersByStatus </strong>function for the<strong> usersToUpdate </strong>param.</p><pre>usersToUpdate chan&lt;- []*User</pre><p>Channels by default are <strong>bi-directional</strong> meaning that you can send and receive information through them, but when passing a channel to a function you can change this behavior and tell the channel that in the context of the function it will only serve one purpose, either to receive information or to send information.</p><p>So in this case, we are telling the channel <strong>usersToUpdate</strong> that in the context of this function this channel will only accept sending information and not receiving it.</p><p>This function <strong>filterNewUsersByStatus</strong> range over the <strong>newUsers</strong> and only selects the ones that are active and has the setting enabled for notifications. After that in line 54, the <strong>filtered users</strong> are sent through the channel.</p><p>At this point, this channel will not be used anymore for sending data so it is important to close the channel. In this case, we are using the <strong>defer</strong> function to call the built-in <strong>close</strong> function and close the <strong>usersToUpdate</strong> channel.</p><p>In the second goroutine, we send the <strong>usersToUpdate</strong> channel, the <strong>userToNotify</strong> channel and the <strong>existingUsers</strong> slice. This is where the concept of using a channel’s results as the input for another goroutine comes into play.</p><p>In this function we are also defining for each channel if it will be used for receiving information or sending information, <strong>usersToUpdate</strong> will be used to only receive data and <strong>userToNotify</strong> to send data.</p><p>In line 59 the function first updated the existing users by appending a new tag to each of them. Then in line 63, it creates a new variable assigning it to the result of the <strong>usersToUpdate</strong> channel. This line will block the execution of this goroutine until the channel sends a message. In other words, if the <strong>filterNewUsersByStatus</strong> takes a lot of time to send the <strong>filteredUsers</strong>, this goroutine will have to wait in this line before proceeding.</p><p>Once the data is received this goroutine ranges over the <strong>newUsers</strong> and also updates their tags, but also sends the user through the <strong>userToNotify</strong> channel in line 68.</p><p>The <strong>userToNotify</strong> will also need to be closed after this function completes its work, so in line 58 we have a <strong>defer</strong> to close the channel.</p><p>Then in line 42, there is a function that is called in the main goroutine, that will notify users, it takes the <strong>userToNotify</strong> channel and the <strong>existingUsers</strong> as parameters.</p><p>This function first initializes a service for sending notifications and then ranges over the existing users and sends an email notification to each of them.</p><p>Then in line 78, it ranges over the <strong>userToNotify</strong> channel, and for each user that is sent through this channel, this function sends an email notification to that user. This syntax allows us to receive all the information sent through this channel and once the channel is closed, the for loop will break too. This will prevent us from reading from a closed channel, as I mentioned before this is one way of ensuring you don’t read from a closed channel. The other syntax is as follows:</p><pre>resp, ok := &lt;-userToNofity</pre><p>The ok variable will be false if we are reading from a closed channel and true otherwise, but it will not panic.</p><p>As you can see in this example the functions will run concurrently and they communicate to each other using channels to send information about the filtered users and the users to notify.</p><p>In this example, we learned how to close a channel using defer and close function.</p><pre>defer close(done)</pre><p>Also how to make a channel uni-directional when it is passed to a function</p><pre>userToNotify &lt;-chan *User // read-only channel<br>userToNotify chan&lt;- *User // send-only channel</pre><p>How to range over a channel, this is useful when we don’t know how many items will be sent through a channel but we want to read all of them.</p><pre>for user := range userToNotify {}</pre><p><strong>Buffered Channels: </strong>This type of channel allows you to store more than one piece of data specified by the capacity, when that capacity is reached, subsequent messages that are sent to the channel will block until at least one message is read so that the channel has capacity again.</p><p>To create a buffered channel we only need to pass an additional parameter to the make function:</p><pre>ans := make(chan int, 5)</pre><p>This channel will accept 5 integers without blocking the goroutine, but if a 6th integer is sent to this channel, then it blocks until a receive operation is performed. The same thing will happen if the channel is empty and a receive operation is performed, it will block until a sent operation is performed.</p><p>The data structure used to keep track of the capacity of the channel is a queue, which means that the first element that gets into the queue will be the first getting out of the queue.</p><p>Let’s look into this using the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/403e512e1c0679b84eacabfdf96a0b3c/href">https://medium.com/media/403e512e1c0679b84eacabfdf96a0b3c/href</a></iframe><p>In the above scenario, we create a buffered channel with a capacity of 3, which means that it can hold 3 strings at a time without blocking the goroutine. In line 10 a goroutine is created and the channel is passed in. That function will send multiple names to the channel with a latency of 1sec between each send, when finishing sending the names the channel will be closed using defer.</p><p>In the main goroutine, there is a sleep function call to simulate that the main goroutine executes another operation that took 5 sec before reading values from the channel.</p><p>Let’s see the output of this code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/1*dh5tis6-N55ZZfgXfghyRQ.png" /></figure><p>As you can see, the first 3 names are sent to the channel without blocking since the buffered size is 3, but after that, the execution of the second goroutine blocks until at least one element is read from the channel, when the main goroutine starts reading from the channel, the second goroutine is unblocked and continues sending the remaining names.</p><h4>Key takeaways</h4><ul><li>Use goroutines to speed up your Go program.</li><li>Use the make keyword to create an unbuffered channel.</li><li>Use the make keyword specifying the capacity to create a buffered channel.</li><li>Read data from a channel with this syntax resp := &lt;-names.</li><li>Send data to a channel with this syntax numbers &lt;- num.</li><li>Read all data sent to a channel using a range for loop.</li><li>Close a channel using the defer and close built-in functions.</li><li>Blocking concepts between different goroutines.</li><li>Change bi-directional channels to behave as sent-only or read-only channels within function contexts.</li><li>Use channels to communicate between different goroutines.</li></ul><p>We’ve seen a lot of concepts related to concurrency in Golang. I hope you enjoyed it and learned from this article!</p><p>Thank you for reading. Stay tuned.</p><h4>Resources</h4><p>If you are interested in learning more about Go, the following articles may be helpful.</p><ul><li><a href="https://betterprogramming.pub/implementing-interfaces-with-golang-51a3b7f527b4">Implementing Interfaces With Golang</a></li><li><a href="https://betterprogramming.pub/go-api-design-with-protocol-buffers-and-grpc-991838e4852b">Go API Design With Protocol Buffers and gRPC</a></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6a616a03839fab78c5eca4dde190a68/href">https://medium.com/media/c6a616a03839fab78c5eca4dde190a68/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55ddb5e1881" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/concurrency-in-golang-goroutines-and-channels-explained-55ddb5e1881">Concurrency in Golang, Goroutines, and Channels Explained</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go API Design With Protocol Buffers and gRPC]]></title>
            <link>https://medium.com/better-programming/go-api-design-with-protocol-buffers-and-grpc-991838e4852b?source=rss-5780cbfd325b------2</link>
            <guid isPermaLink="false">https://medium.com/p/991838e4852b</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Yair Fernando]]></dc:creator>
            <pubDate>Thu, 19 May 2022 15:12:46 GMT</pubDate>
            <atom:updated>2022-12-30T03:35:24.520Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step guide based on a social media app</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJu8bnI-h8x1nYJG5SF2Jw.png" /></figure><p>When building APIs using gRPC, the API design is commonly built using protocol buffers to define API endpoints, request messages, and response messages. This is typically accomplished using proto files that can later be used to generate the go code to make actual RPC calls and also to generate a reverse proxy to translate gRPC into JSON APIs, etc.</p><p>I’d recommend reading the articles in the following order:</p><ol><li>Go API Design With Protocol Buffers and gRPC</li><li><a href="https://betterprogramming.pub/building-reverse-proxy-grpc-gateway-621696b29b0">Building Reverse Proxy (gRPC-Gateway)</a></li><li><a href="https://yairfernando.medium.com/go-api-database-connection-d47e463cea37">Go API — Database Connection</a></li></ol><p>In this article, we’ll focus on the following:</p><ul><li>building API design using protocol buffers</li><li>creating endpoints</li><li>defining request messages</li><li>defining response messages</li><li>using enumerables</li><li>handling timestamps</li><li>returning empty responses</li></ul><p>I won’t go into details on what gRPC is or why you should use protocol buffers as opposed to JSON, but if you are interested in getting to know more, here’s another <a href="https://levelup.gitconnected.com/grpc-how-to-make-effective-unary-calls-4c9fa68cd9d5">article</a> that explains a bit more about it.</p><p>For this article, the API design will be based on a social media app.</p><p>Before jumping in, it is important to mention that I’ll be using Go modules. So, to follow along in this series, it’ll be necessary to have Go modules working correctly on your machine since we’ll be testing the API in a Go application later.</p><p>First, let’s navigate to the $GOPATH using this command:</p><pre>cd $GOPATH</pre><p>Then create or navigate to the following path:</p><pre>cd src/github.com/YourGithubHandle/sma</pre><p>Creating this path now will be helpful later because we’ll eventually push this code to GitHub.</p><p>Once we are in the sma folder, which stands for social media app, let’s initialize a Go module.</p><pre>go mod init github.com/YourGithubHandle/sma</pre><p>This command will create the go.mod file for us.</p><p>Then we’ll create the posts.proto file under protos.</p><p>So, let’s create that folder and put the posts.proto file inside it.</p><figure><img alt="protos/, posts.proto, go.mod, go.sum" src="https://cdn-images-1.medium.com/max/354/1*gynYdq1EnrIWHHlIeNHxrg.png" /></figure><p>We’ll first define the create endpoint. This endpoint will receive a request message with some parameters, and it will return a response message notifying us that the post object was created.</p><p>Let’s see the definition below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/839a8c89582f4caec2874089e5f3abbf/href">https://medium.com/media/839a8c89582f4caec2874089e5f3abbf/href</a></iframe><p>The first line of this proto file defines which proto syntax we are using. In this case, that’s the proto3 syntax. If this line is not specified, the protobuf compiler will assume the proto2 syntax is being used. If you want to explore more about their differences, here is the <a href="https://developers.google.com/protocol-buffers/docs/proto3">proto3</a> and <a href="https://developers.google.com/protocol-buffers/docs/proto">proto2</a> documentation.</p><p>In line 3, we have the package definition. This can help you avoid name clashes if you need to define the same message definition under a different package name.</p><p>Then we also have the option go_package. In Golang’s case, this will be used as the package name, but for this example, it is the same as the original package name. If you need it to be different, you can use this option.</p><p>Then we have an import. This import allows us to properly serialize created_at and updated_at timestamp. This import is literally another proto file <a href="https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/timestamp.proto">timestamp.proto</a> that protobuf will use to handle timestamps. Just like we are importing this external proto file, we will be using other external proto files for different purposes.</p><p>Also, we can use definitions from other proto files we own if we needed, including ones that don’t come from Google. We’ll be covering that later.</p><p>In line 9, we have the service definition for Posts. By defining a service in a proto file, we can generate Go code when the protocol buffer compiler uses this file. It will generate server and client interfaces with all the code to make RPC calls.</p><p>We define the endpoint that we’ll want to support within this service. In this case, we have the create post endpoint, which takes the CreatePostReq and returns the created Post object.</p><p>Let’s focus on the CreatePostReq message first.</p><p>This message defines the parameters this endpoint will accept in the request.</p><p>The structure is first defining the field’s type, then the field’s name, and then the field’s number.</p><p>The field’s type specifies the data type of this param, either a string, integer, boolean, float, double, bytes, etc.</p><p>The field’s name is just the name of the param itself.</p><p>The field’s number is the unique number that is used to identify each field in the binary format. And should not change once your message type is already being used. One important thing to note here is that you should try to reserve the numbers from 1 to 15 for the most important and frequent fields in your message.</p><p>This is because the field numbers from 1 to 15 take one byte to encode and from 16 to 2047 take two bytes. So, it is perfectly fine if you have 10 fields in a message that goes from 1 to 10, and then two other fields that have a field number greater than 15 because you want to reserve those five numbers for future fields.</p><p>The last thing to mention about this CreatePostReq message is the last field has an extra word at the beginning of the definition. This is because this last param is an array, and the way to represent this in protocol buffers is using the repeated word at the beginning of the field definition. The default value of a repeated field would be an empty list or array, depending on the programming language this message is translated to.</p><p>Let’s now inspect the definition of the Post message. The first four fields are self-explanatory, so let’s go to the status field. Here we are using an enum (defined in line 50) as the field’s type. Using an enum will ensure this field only accepts one of the options in the enum. If no value is passed, the enum value with the field number of 0 will be the default.</p><p>A couple of considerations for enums are that it has to have a zero value since the zero value is considered the default value. Another thing is that for compatibility with proto2 syntax, the zero value has to be the first element in the enum.</p><p>Finally, we have the created and updated fields in the Post message, and here the field’s type is google.protobuf.Timestamp, which is, in turn, has another protobuf message with two fields: seconds and nanos.</p><p>We’ll be adding more endpoints to this file, but for now, let’s go ahead and generate the Go code for this proto file.</p><p>First, let’s install protobuf with this command:</p><pre>brew install protobuf</pre><p>We’ll also need to install protoc-gen-go and protoc-gen-go-grpc, as shown below:</p><pre>go install google.golang.org/protobuf/cmd/protoc-gen-go@latest<br>go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest</pre><p>Then make sure you update your path</p><pre>export PATH=&quot;$PATH:$(go env GOPATH)/bin&quot;</pre><p>After that, make sure “enable module” is on</p><pre>export GO111MODULE=on</pre><p>If you type protoc, you should see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*MSyayd0ZxWjE_baHhcuB5w.png" /></figure><p>Now, let’s navigate to the protos folder and run the following command to generate the Go code. Before doing this, make sure you create the src/go/sma folder structure.</p><pre>protoc --go_out=src/go/sma \<br>       --go_opt=paths=source_relative \<br>       --go-grpc_out=src/go/sma \<br>       --go-grpc_opt=paths=source_relative \<br>       posts.proto</pre><p>This will generate the Go code with the Posts service and endpoint definitions.</p><figure><img alt="protos/, src/go/sma/, posts.pb.go, posts_grpc.pb.go, posts.proto, go.mod, go.sum" src="https://cdn-images-1.medium.com/max/349/1*Mg2N5qHDoM80-bOq07vU1A.png" /></figure><p>Great! We’ve generated the code for the Posts service containing the create endpoint.</p><p>To continue building the Posts service, we need to add the UPDATE, SHOW, LIST, and DELETE endpoints.</p><p>Here’s the definition for the update endpoint:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80c063b743a89cc30967742d72d63c95/href">https://medium.com/media/80c063b743a89cc30967742d72d63c95/href</a></iframe><p>As usual, we define the RPC endpoint with a request message and a response message. That is not new at this point. Let’s examine the <strong>UpdatePostReq</strong> message definition.</p><p>The first field of this message is update_mask , and its type is google.protobuf.FieldMask.</p><p>Field masks are used for two things, either to explicitly define the set of fields that should be returned by a get operation or the fields that will be updated in the case of an update operation. It filters out the fields sent in a patch request and only leaves or allows the ones specified in the mask.</p><p>For a get operation, it will take the response and only return the fields that are present in the mask. The remaining fields will default to the default value of the data type they hold. For endpoints that return a collection of objects, the field mask will apply to each object in the collection. In this case, the mask object is the last field in this message.</p><p>Later, we’ll see how this field is used when we write the annotations for this proto file. One thing to note here is that the REST verb for this endpoint will be PATCH since we are using a field mask. PUT is only used for full updates.</p><p>On line 8, we have the import of this proto file to use FieldMask.</p><p>UpdatePost holds the permitted attributes to be updated. This means that the endpoint will permit the title, description, media_ids, and schedule_at attributes to be updated.</p><p>PostId is the id of the post to be updated.</p><p>All right, let’s move on to the show endpoint, which is shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4a72cee0233281732ccdc155c6c7c71/href">https://medium.com/media/d4a72cee0233281732ccdc155c6c7c71/href</a></iframe><p>This is a pretty simple one. In the PostIdReq message, we have only one field, which is the post_id of the post we want to show. As a response, we return the Post message we declared before.</p><p>Here’s the code for the ListPosts endpoint definition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/578f3635323233de6e6507c218cdbafb/href">https://medium.com/media/578f3635323233de6e6507c218cdbafb/href</a></iframe><p>For this endpoint, we’ll return the collection of posts associated with a given user so that the user id will be needed in the request message.</p><p>If we take a look at the ListPostsReq message, the first field is the actual user_idThe next one is a search query string in case we want to search through the collection. It also has page and per_page fields to specify which page to return and how many elements each page should have.</p><p>The last element is the filter, and here again, we have an enum representing the type of this field, which means we can only filter by the elements specified in the Filters enum, which maps the posts’ statuses.</p><p>In ListPostsResp, we have only two fields. The first one represents the collection of posts that will be returned, and the second one focuses on the pagination data object.</p><p>Finally, let’s see the definition of the delete endpoint:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0913c4a8033a30841e9ffedb8fa6979/href">https://medium.com/media/c0913c4a8033a30841e9ffedb8fa6979/href</a></iframe><p>This endpoint is pretty simple; it takes the PostIdReq we previously defined and returns an empty response message.</p><p>Let’s also update the CreatePostResp message to add the scheduled_at field since I added it in the UpdatePost endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*DIENNtqtrbFTGZqh98GpJA.png" /><figcaption>CreatePostResp updated. Code below.</figcaption></figure><p>We are done with the API for the Posts service.</p><p>Here’s the entire proto file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8f7a0d9f1207efc8ba2cf44466dfed6/href">https://medium.com/media/f8f7a0d9f1207efc8ba2cf44466dfed6/href</a></iframe><p>Now, let’s generate the Go code for this service.</p><p>To avoid having to remember the last protoc command we ran to generate the Go code, let’s create a Makefile under the protos folder with the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*CikSI3P8DhUbmCPggSQqWQ.png" /><figcaption>Makefile</figcaption></figure><p>Now, let’s open the terminal under the protos folder and run the make command:</p><pre>make proto proto_file=posts.proto</pre><p>This will generate the Go code! Great, we have defined the API endpoints for the Posts resource using protocol buffers and gRPC!</p><p>The folder structure looks like this:</p><figure><img alt="protos/, src/go/sma/,posts.pb. go, posts_grpc.pb.go,makefile, posts.proto, go.mod, go.sum, readme.md" src="https://cdn-images-1.medium.com/max/357/1*OBADzWjpGTjHerymMMJgEw.png" /><figcaption>Folder structure</figcaption></figure><p>Let’s now see how to generate swagger and openapi documentation for the Posts API.</p><p>First, let’s define the service configuration file for the posts.proto file. This file contains the HTTP configurations and mappings from gRPC to REST API.</p><p>Create a new file inside the protos folder and call it posts_annotations.yml . The code follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4e829831c51d9a0d0c350d1c080ed90/href">https://medium.com/media/d4e829831c51d9a0d0c350d1c080ed90/href</a></iframe><p>Here we have the HTTP rules for each endpoint from the posts.proto file.</p><p>The selector specifies the RPC endpoint, and then we specify the HTTP verb followed by the rest path we want to map this endpoint to. Here we specify the parameters that must be in the path. In this case, the user_id and the post_id depend on each endpoint.</p><p>In the UpdatePost endpoint, we used a field mask, and we called the updatable object Post. That is why the body has a string that says “post.” This is referring to the Post message we have in the UpdatePostReq message.</p><p>Run this command to install swagger and protoc-gen-openapiv2:</p><pre>go install github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger@latest<br>go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2@latest</pre><p>Let’s create two new folders. Under src, create the swagger folder and the openapi folder.</p><p>Now, we need to extend the command in the Makefile to generate the API documentation with swagger and openapi. We will also include the command to generate the gateway Go code so that our API is ready to implement a reverse proxy.</p><p>The new command looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aaca1bcf536d489835ecd6e2c3d6d9ef/href">https://medium.com/media/aaca1bcf536d489835ecd6e2c3d6d9ef/href</a></iframe><p>Let’s generate the code.</p><pre>make proto annotation_file=posts_annotations.yml proto_file=posts.proto</pre><p>This will create the swagger JSON files and also a new file posts.pb.gw.go, which contains the code to implement a reverse proxy.</p><p>This is the new folder structure after running the make command:</p><figure><img alt="protos, src, go/sma, posts.pb.go, posts_grpc.pb.go, openapi, posts.swagger.json, swagger/, posts.swagger.json, makefile, posts.proto, posts_annotations.yml, go.mod, go.sum, readme.md" src="https://cdn-images-1.medium.com/max/340/1*P0WpdjKKctwQgPyklPFIAA.png" /><figcaption>Folder structure</figcaption></figure><p>Great. We have covered a lot, and our API design is ready to be used in a gRPC project. If you want to see how to implement the reverse proxy and consume this API, leave a comment!</p><p>Thank you for reading. Stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=991838e4852b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/go-api-design-with-protocol-buffers-and-grpc-991838e4852b">Go API Design With Protocol Buffers and gRPC</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Binary Search Tree Data Structure.]]></title>
            <link>https://medium.com/geekculture/binary-search-tree-data-structure-part-1-e3842f4cfbc5?source=rss-5780cbfd325b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3842f4cfbc5</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Yair Fernando]]></dc:creator>
            <pubDate>Fri, 12 Mar 2021 05:03:53 GMT</pubDate>
            <atom:updated>2022-06-17T01:39:03.377Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pv2AJGKWmqbFC9NjAWXuCg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@isaacmsmith?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Isaac Smith</a> on <a href="https://unsplash.com/s/photos/data-structures?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Choosing between different data structures to store data can be tricky if we don’t understand the differences between them. For instance, we can use an array or a linked list to store data, both are linear data structures that allow you to store data in a linear way. There are different advantages and disadvantages over one another.</p><p>In this article, we’ll talk about another data structure that can give you better performance than the two data structures mentioned above — I’m talking about a <strong>Binary Search Tree.</strong></p><p>This article assumes some basic knowledge about data structures and Big O notation.</p><p>Let’s dive right into some concepts that will help us better understand what this data structure is all about.</p><p>A <strong>Binary Search Tree or BST</strong> is a specific type of tree so let’s start by defining what a Tree is.</p><h3>Tree</h3><blockquote>A Tree is a non-linear data structure that is composed of nodes, where each node in the tree can have many child nodes and every node can hold some data. The first node in a tree is called the root, nodes in the same level that shared the same parent are called siblings.</blockquote><h3>What is a Binary Search Tree?</h3><p>A BST is a specific type of Tree that follows certain validations. For instance, in a BST every node can have at most two children and all nodes to the left side should be less than the parent node, as well as all the nodes to the right side should be greater than the parent node.</p><p>A Binary Search Tree is not a linear data structure because there are multiple different ways to iterate a tree, since we have nodes to the left and right sides we can take different directions when iterating over the tree.</p><p>When we create a BST we usually want to iterate and list all its elements store in the tree, just like we do when using linear data structures like arrays or linked lists. This process is called <strong>tree traversal,</strong> and it means that we process the tree in a specific way that we can visit every node only one time.</p><p>Now let’s see how a BST looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*fpURGBBnNid5swdrM2CTGA.png" /><figcaption>Binary Search Tree</figcaption></figure><p>As I mentioned before every node to the left side is less than the parent node and every node to the right side is greater than the parent node.</p><p>Now to traverse this tree we have different options, let’s look at them one by one.</p><h3>Breadth-First Traversal</h3><p>When using this technique to traverse a tree we go from left to right on each level visiting each node. We start at the root node of the tree. <strong>Level Order Traversal </strong>also refers to the same traversal strategy<strong> </strong>because we go level by level visiting each node in the tree until we reach the end.</p><p>We can use this technique when looking for the shortest path between any two nodes in the tree. Implementing a Breadth-First Traversal with the help of a Queue data structure would take<strong> BigO(n)</strong>.</p><p>Traversing and printing the values from the BST shown above using Breadth-First Traversal would look like this: 25, 20, 34, 15, 22, 29, 39, 27, 31<strong>.</strong></p><h3>Depth-First Traversal</h3><p>There are three ways of traversing a tree using Depth-First Traversal — preorder traversal, inorder traversal, and postorder traversal.</p><h4><strong>Preorder Traversal </strong>(Root, Left, Right)</h4><p>We first visit the root node, then the left node, and then the right node until we traverse the entire tree. This method is useful when we want to perform a search operation or process the root node before moving to the child nodes. Traversing and printing the values from the BST shown above using Depth-First Traversal would look like this: 25, 20, 15, 22, 34, 29, 27, 31, 39.</p><h4><strong>Inorder Traversal </strong>(Left, Root, Right)</h4><p>We first visit the left node, then the root node, and then the right node until we traverse the entire tree. If we apply inorder traversal to a BST we’ll get the values in ascending order. That is something that we’ll want to achieve very often when using a tree. Traversing and printing the values from the BST shown above using Depth-First Traversal would look like this: 15, 20, 22, 25, 27, 29, 31, 34, 39.</p><h4><strong>Postorder Traversal </strong>(Left, Right, Root)</h4><p>We first visit the left node then the right node, and then the root node until we traverse the entire tree. This is useful when we need to perform some operations on the child nodes first before visiting the root. Traversing and printing the values from the BST shown above using Depth-First Traversal would look like this: 15, 22, 20, 27, 31, 29, 39, 34, 25.</p><p>There are two ways of implementing any of these three methods I just mentioned above — The first one is using recursion, and the second one is using another data structure called a stack.</p><p>There are a couple of things to consider when choosing between these two techniques to iterate a BST. If you can tell that the data you are looking for is near the root node, you can go with Breadth-First Traversal, but if you know that the data you are looking for could be very deep in the tree then using Depth-First Traversal might be a better approach.</p><h3>BigO Notation for a BST</h3><p>So far we talked about the definition of a BST, and the different strategies to traverse it. But, what are the advantages of using a BST over a linear data structure such as an array or a linked list?. Well, everything lays down to the run time complexity we can achieve when using a Binary Search Tree in operations like insertion, deletion, and searching.</p><p>For instance, arrays and linked lists give <strong>BigO(n)</strong> in search operations, <strong>BigO(1)</strong> in insert operations, and <strong>BigO(n)</strong> in removal operations, but we can do better with BST. Now if we have a sorted array, we could perform a <strong>binary search</strong> <strong>algorithm</strong> to search for elements, and the run time complexity would be <strong>BigO(log n)</strong> which is better than using an unsorted array or a linked list.</p><p>If you haven’t heard of what the binary search algorithm is all about, let’s defined it here.</p><p>Binary Search is an effective algorithm to perform search operations over a sorted array. The way it works is that it compares the value you are looking for with the middle element in the array. If the value is greater than the middle element, the algorithm discards the left half of the array and will continue searching on the right side. If the value is less than the middle element, the algorithm discards the right half of the array and will continue searching on the left side.</p><p>But even for a sorted array, we still have <strong>BigO(n)</strong> for inserting and deleting operations. Here is when we want to use a BST because we will still have the ability to perform a <strong>binary search algorithm</strong> and have <strong>BigO(log n)</strong> for all three operations. The only thing to consider is that if we want to have always <strong>BigO(log n)</strong> in a BST we have to keep the tree balanced.</p><p>For example, if we have a BST like the following, we won’t have any advantages over using an array because the tree is not balanced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*ZSew33mQZ8b2qRdz6kHlHg.png" /><figcaption>Unbalanced Binary Search Tree</figcaption></figure><p>Now let’s see how searching and inserting into a BST would look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*9wWwq_wKjYWMWG-abCtIpQ.png" /><figcaption>Search on a Binary Search Tree</figcaption></figure><p>As you can see to search for an element inside the tree we can just validate that the value we are looking for is less or greater than the value of the current node, and based on that move to the left or right. In this case, 14 is greater than the root node, so we move to the right, then we check if the next value is less or greater than the value we are looking for again, and this time is greater, so we move to the left. And at this point, we have found the element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*RijRrv6_XR84jnAhc7S6YQ.png" /><figcaption>Insert on a Binary Search Tree</figcaption></figure><p>For inserting an element in a BST, we follow some similar validations, we start at the root node of the tree and validate if the value we want to insert is less than the current node value and if it is we also check if the left node is not null, if it is not null we move to the left side but if it is null we insert the value to the left of the current one. And the same applies to the right side in case the value is greater than the root node value. So in this example, we keep validating the same traversing from value 12 to 10, then to 5, and finally to 7. When we reach this point we run the same validations but this time the left node of 7 is null so we insert the value to the left side of the current node and we are done!!</p><p>Now for traversing and printing the value of each node we could use any of the three methods I mentioned above that are part of the Depth-First Traversal strategy. The run time complexity of doing this would be <strong>BigO(n)</strong> because the amount of effort to traverse the entire tree is proportional to the number of nodes we have in the tree. So just like with arrays or a linked list the run time complexity to traverse the entire tree is linear.</p><h3>Conclusion</h3><p>Use a BST whenever you want to optimize operations like insertion, deletion, and searching over a collection of elements. Using a BST is quite better than a linked list or array. The only advantage of using an array over a BST is the <strong>BigO(n)</strong> that arrays give when accessing an element.</p><p>We can use BST as an efficient data structure to store and search for data. The advantage of using a BST over a linked list or array is that it gives us better run time complexity.</p><p>Thank you for taking the time to read this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3842f4cfbc5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/binary-search-tree-data-structure-part-1-e3842f4cfbc5">Understanding Binary Search Tree Data Structure.</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>