<?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 Alessandro Petraro on Medium]]></title>
        <description><![CDATA[Stories by Alessandro Petraro on Medium]]></description>
        <link>https://medium.com/@alessandropetraro?source=rss-76aa37aaa799------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ttnVsVagSBU6rXpZ</url>
            <title>Stories by Alessandro Petraro on Medium</title>
            <link>https://medium.com/@alessandropetraro?source=rss-76aa37aaa799------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:16:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alessandropetraro/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[Solana — Understanding Programs]]></title>
            <link>https://medium.com/better-programming/solana-understand-programs-a7d2d15f32fa?source=rss-76aa37aaa799------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7d2d15f32fa</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[solana-network]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alessandro Petraro]]></dc:creator>
            <pubDate>Mon, 29 Aug 2022 20:02:59 GMT</pubDate>
            <atom:updated>2022-09-20T14:34:12.793Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dive into what’s behind the curtains</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DlC_F-pk9UlkMAwz" /><figcaption>Photo by <a href="https://unsplash.com/@theshubhamdhage?utm_source=medium&amp;utm_medium=referral">GuerrillaBuzz Crypto PR</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a> — <a href="https://guerrillabuzz.com/">https://guerrillabuzz.com</a></figcaption></figure><p>This article is the article I would love to have found when getting started with <a href="https://solana.com/">Solana</a> programs development. Out there, in fact, there is plenty of resources that teach you how to build Solana programs, but I have not found one complete enough to allow you to really understand what is happening behind the curtains.</p><p>In this article I am gonna explain the following:</p><ol><li>Basic notions on Solana programs and accounts</li><li>Basic Solana program structure</li><li>Where to go from here</li></ol><p>By the end of the article you should be able to understand what the Rust process_instruction does behind the curtains.</p><p>I hope this can boost your journey :) Let’s dive in.</p><h3>1 — Solana Programs &amp; Accounts</h3><p>If you are coming from the Ethereum world, a Solana program basically is a Smart Contract. The main thing I struggled with at the very beginning was that in Solana Programs are “stateless”. In other words, while in the Ethereum world you can, for example, create a <em>Counter </em>smart contract and store the value of the <em>counter</em> inside the smart contract itself, this is not possible on Solana. In order to store data on Solana, you need to use Accounts.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FRkzMtKbCKFUY3wYRMy%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FRkzMtKbCKFUY3wYRMy%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FRkzMtKbCKFUY3wYRMy%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a4878e051f160a01c23553b747769fa/href">https://medium.com/media/4a4878e051f160a01c23553b747769fa/href</a></iframe><p>Let me clarify this. As a generalisation you can think of the Solana world as a world dominated by Accounts. A Solana program, in fact, is simply an account marked as executable. From the <a href="https://docs.solana.com/terminology#account">Solana official documentation</a> we read that an account is:</p><blockquote>A record in the Solana ledger that either holds data or is an executable program.</blockquote><p>In Solana, other than Data Accounts and Program Accounts there are also <a href="https://docs.solana.com/developing/runtime-facilities/programs">Native accounts</a> that indicates native programs on Solana. One of the most important is the System Program. This program is important because every new account on Solana is by default owned by the System Program.</p><p>In order to complete our account knowledge, we can say that an account has:</p><ol><li>An Owner → This must be a program and by default is the System Program</li><li>A Holder → This is the person who owns the private key for the account</li><li>Is always addressable by a public key</li><li>Can hold both data (if not executable) and SOL (the Solana native token)</li></ol><p>This raises an important question. If I am not the owner of my Account, how can I transfer SOL from/to my account? On Solana, while crediting an account can be done by anyone, only the account owner can debit the account and change its data.</p><p>Solana achieves this in the following way:</p><ol><li>The account holder must sign an instruction with its private key</li><li>The instruction has to be sent to the System Program (that is the account owner and for this the only one allowed to debit the account and change its data)</li><li>The System Program checks the private key against the account public key and if the check is ok, the transfer is authorised</li></ol><p>I hope that this clarified Programs and Accounts in Solana. Now we are ready to see some code.</p><h3>2 — Program Structure</h3><p>If you are familiar with REST api, when you write a Program on Solana chain you need to define what are the instructions your program will be able to process as they were the endpoint of your web-server.</p><p>A function signature usually takes the following arguments:</p><ul><li>The program id → This is the public key of the currently executing program</li><li>The accounts that the program may read from and write to during this transaction. An account’s place in the array signifies its meaning, for example, when transferring money an instruction may define the first account as the source and the second as the destination</li><li>Additional data specific to the function</li></ul><p>In plain Rust code this translates to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e378304ff55cb008f31acc98dda43c3/href">https://medium.com/media/2e378304ff55cb008f31acc98dda43c3/href</a></iframe><p>It is important to notice that Solana wants you to pass to the functions all the accounts involved in the transaction. This allows Solana to optimise the throughput of the transaction itself by parallelising transactions that involve different accounts.</p><p>In other words, the runtime can look at all the incoming transactions of a program (and even across programs) and can check whether the memory regions in the first argument of the transactions overlap. If they don’t, the runtime can then run these transactions in parallel because they don’t conflict with each other. Even better, if the runtime sees that two transactions access overlapping memory regions but only read and don’t write, it can also parallelise those transactions because they do not conflict with each other!</p><p>For the sake of an example, let’s focus on the <a href="https://github.com/solana-labs/example-helloworld">Hello World example</a> provided by Solana. In this example, we want to store the amount of time we greeted a specific account. Since programs are stateless in Solana, we need to have at least:</p><ol><li>A <em>HelloWorld</em> executable program (aka. Program Account) that can process our instruction</li><li>One or multiple <em>GreetingAccount</em> (one for each account you want to greet). Those will be not-executable programs (aka. Data Accounts) that can store the number of time they have been greeted. Those accounts must be owned by the HelloWorld program in order to enable it to make changes</li></ol><p>Regarding bullet point 1, we can simply deploy our HelloWorld program using <a href="https://docs.solana.com/cli/deploy-a-program">Solana CLI</a>.</p><p>Regarding bullet point 2, we can create the greeted account when it does not exist before performing the Hello and transfer the ownership to the HelloWorld program (for full client code check out <a href="https://github.com/solana-labs/example-helloworld/blob/master/src/client/hello_world.ts#:~:text=//%20Check%20if%20the%20greeting%20account%20has%20already%20been%20created">here</a>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a7c0f3c82e9f555e4111f5f3afcd6a2/href">https://medium.com/media/8a7c0f3c82e9f555e4111f5f3afcd6a2/href</a></iframe><p>Now the process_instruction Rust code should be far more clear. Let’s have a look:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3905fa4415ee19f6c1e56d6cd137f2e9/href">https://medium.com/media/3905fa4415ee19f6c1e56d6cd137f2e9/href</a></iframe><p>Let’s dive in:</p><ol><li>We get the greeted account value from the accounts list using the next_account_info util from Solana</li><li>We check if the HelloWorld program id is an owner for that account and for this ability to make changes. If not we throw an error</li><li>If everything is fine:<br>- We deserialise the account using borsh<br>- We increment the counter inside the data property<br>- We serialise the account back with the new data</li></ol><h3>Where to go from here</h3><p>As you may have noticed, basic Solana code contains a lot of boilerplate (e.g. params serialisation and deserialisation, account validations…) <br>For this, <a href="https://github.com/coral-xyz/anchor">Anchor</a> is a framework that helps with this allowing you to create Solana Programs faster and mainly focussing on the business logic of your program.</p><p>Now, you might be wondering why not starting from Anchor instead of doing Solana plain :) In general, I believe that starting from scratch is always a good way to understand how abstractions could be working on top and allow you to make conscious choices when developing.</p><h3>References</h3><ul><li><a href="https://solana.com/">Solana</a></li><li><a href="https://book.anchor-lang.com/prerequisites/intro_to_solana.html">Intro to Solana</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7d2d15f32fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/solana-understand-programs-a7d2d15f32fa">Solana — Understanding Programs</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[Learning go in 2022 — Boost your journey (part 2)]]></title>
            <link>https://blog.devgenius.io/learning-go-in-2022-boost-your-journey-part-2-2c23c401c7b5?source=rss-76aa37aaa799------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c23c401c7b5</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Alessandro Petraro]]></dc:creator>
            <pubDate>Tue, 03 May 2022 11:59:42 GMT</pubDate>
            <atom:updated>2023-01-26T09:51:51.661Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*1XlW6esECPCnxEcuEvwIrQ.png" /><figcaption>credits to: <a href="https://github.com/MariaLetta/free-gophers-pack">https://github.com/MariaLetta/free-gophers-pack</a></figcaption></figure><h3>Learning go — Boost your journey (part 2)</h3><p>This article is the second part of Learning go — Boost your journey. If you missed the first part, check it out <a href="https://blog.devgenius.io/learning-go-in-2022-boost-your-journey-6edc606ed030">here</a>.</p><p>In this article, I would like to focus on some <strong>“advanced” Go functionalities</strong> that can boost your programming experience and can help you start building Go applications with <strong>concurrency</strong> in mind:</p><ul><li>Goroutines</li><li>Channels</li><li>Goroutine Synchronisation</li><li>Select — Multi-channel operations</li><li>Atomic Counters and Mutex</li></ul><p>So, let’s get started :)</p><h3>Goroutines</h3><p>As we can read in <a href="https://gobyexample.com/goroutines">go by example</a> a Goroutine is a <strong>lightweight thread of execution</strong>. Goroutines are like threads, but cheaper and can <strong>run concurrently</strong> with other functions and methods.</p><p>Given a function printSomething, in order to run it inside a Goroutine, you can simply write: go printSomething(). Go also supports running Goroutines as <strong>anonymous functions</strong> with the syntax: go func() { ... do something ...}()</p><p>When we launch a Go program, by default a Main Go Routine is run. This special Go routine controls when the program exits and for this if you create one ore more child Go routines, you need a way to wait them to finish before exiting the program.</p><p>In order to do this, Go offers a nice mechanism to make them communicate and synchronise: <strong>channels</strong>.</p><h3>Channels</h3><p>We can see a channel as a <strong>pipe</strong> that helps us <strong>connecting</strong> and <strong>synchronising</strong> <strong>concurrent Goroutines.</strong> Let’s see some basic syntax for channels to speed up our development:</p><ul><li><strong>Creating</strong> a channel: make(chan val-type) <em>(e.g. </em><em>make(chan string))</em></li><li>Send a value (<strong>write</strong>)<strong> </strong>over a channel: channel &lt;- myValue</li><li>Receive a value (<strong>read</strong>) from a channel: myVar := &lt;- channel</li><li><strong>Closing</strong> a channel: close(channel). Closing a channel means that <strong>no more values will be sent on it</strong> and can be useful to communicate to receivers that no more messages will be sent over the closed channel.<br>It is always possible to close a non-empty channel, but still have the remaining values be received</li><li>When passing channels to functions you can mark them as <strong>readonly</strong> / <strong>writeonly</strong> channel with the syntax:<br>– readonly → func f(myReadOnlyChannel &lt;-chan string) <br>– writeonly → func f(myWriteOnlyChannel chan&lt;- string)</li></ul><p>It is really important to know that <strong>by default:</strong></p><ol><li><strong>Send</strong> and <strong>Receive</strong> are <strong>blocking</strong>. This means that every time: <br>– You send a value over a channel, the thread blocks waiting for the message being received<br>– You receive a value from the channel, the thread blocks waiting for a message being present in the channel</li><li>Channels are <strong>unbuffered </strong>meaning their <strong>buffer capacity is zero. </strong><br>With buffer capacity I mean the <strong>amount of messages</strong> your process can send / receive <strong>before blocking</strong></li></ol><p>Unbuffered channels coupled with send and receive blocking syntax make your Go program a good candidate for <strong>deadlocks</strong> if you do not know what you are doing.</p><p>Let’s see an example to be more clear:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/216e338d4d70ed452d6c65352b32c7be/href">https://medium.com/media/216e338d4d70ed452d6c65352b32c7be/href</a></iframe><p>We can <strong>overcome the deadlock </strong>above in two ways:</p><p>(1) Using a <strong>buffered channel → </strong>In this kind of solution, we are kind of hacking the default Go channel semantic, making it not blocking until the buffer limit is reached</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70bb7363e7709c642aad0c8f56cf0711/href">https://medium.com/media/70bb7363e7709c642aad0c8f56cf0711/href</a></iframe><p>(2) Using a <strong>Goroutine → </strong>With this solution, we keep Go blocking semantics unaltered and we introduce a concurrent thread of execution to avoid the deadlock</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9eb9934ce9f587622ec535fb2a7d0b7/href">https://medium.com/media/b9eb9934ce9f587622ec535fb2a7d0b7/href</a></iframe><h3>Goroutines Synchronisation</h3><p>Channels can be useful to <strong>synchronise</strong> execution across multiple <strong>Goroutines. </strong>In Go the synchronisation can be obtained in different ways depending on the use case.</p><p>(1) When <strong>dealing</strong> with a <strong>single Goroutine</strong>, a bool channel can do the trick</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddec702f6c230c5f78ef4b6b152074a5/href">https://medium.com/media/ddec702f6c230c5f78ef4b6b152074a5/href</a></iframe><p>(2) For more complex scenarios involving <strong>multiple Goroutines</strong>, we can instead leverage on the built in Go WaitGroup made available by the package sync</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4201d85ef7b25f71c82a778608bdc11/href">https://medium.com/media/d4201d85ef7b25f71c82a778608bdc11/href</a></iframe><p><strong>Note:</strong> if a WaitGroup is explicitly passed into functions, it should be done by pointer</p><h3>Select — Multi-channel operations</h3><p>When dealing with multiple channels, Go offers a really powerful programming construct that helps us make our code cleaner: <strong>Select.</strong></p><p>Select allows you to <strong>wait on multiple channels operations</strong>. You can think about Select as if it was a switch...case where, instead of switching on a condition, you are <strong>selecting</strong> the <strong>code</strong> to be <strong>executed depending on </strong>which <strong>channel</strong> is <strong>unblocked</strong> by receiving / sending a message. In fact, as mentioned above, Go channels are unbuffered and have a blocking semantic by default.</p><p>As in a switch...case the default case is executed where no condition is met and this in the select statement translates into: no channel received a message or no channel was able to send a message. As you may notice, having a default case convert the select semantic from blocking to not blocking.</p><p>In the following example I simply:</p><ol><li>Create 2 channels</li><li>Start a Goroutine that, inside an infinite loop, using a select print a message</li><li>Goroutine and main process are synched using a simple bool channel</li></ol><p>Let’s see a simple example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17451f7f7dd258895870de2ed515c39e/href">https://medium.com/media/17451f7f7dd258895870de2ed515c39e/href</a></iframe><h3>Atomic Counters &amp; Mutex</h3><p>The main mechanism for managing state in Go is communication over channels, but there exist a few other options that is worth mentioning.</p><ol><li><strong>Atomic package →</strong> As mentioned in the <a href="https://pkg.go.dev/sync/atomic">official documentation</a> all the functions contained inside the atomic package require <strong>great care to be used correctly</strong>. For this reason, except for special, low-level applications, they suggest doing synchronisation with channels or the facilities of the sync package. Anyway, one use case for the atomic package could be building a simple <strong>atomic counter.</strong> For example, in order to atomically add 1 to a Goroutine shared variable myCounter you can simply import the sync/atomic package and use it like: <br>atomic.AddUint64(&amp;myCounter, 1)</li><li><strong>Mutex → </strong>Mutex can be used to handle more complex state. As stated in the <a href="https://pkg.go.dev/sync#Mutex">official documentation</a>, the zero value for a Mutex is an unlocked Mutex. The main operations that you can do on a Mutex are:<br>– <strong>Declaration</strong> → var myMutex sync.Mutex. <strong><br></strong>– <strong>Lock</strong> → myMutex.Lock() (blocks until mutex available)<br>– <strong>Unlock</strong> → myMutex.Unlock() (throws if the mutex is not locked)</li></ol><h3>Conclusions</h3><p>This is only an introduction to Goroutines and Channels, but I think that mastering those concepts can help you building solid foundations for your next Go project.</p><p>If you enjoyed the article and you want to let me know, just leave me some claps 👏 and if you do not want to miss my next articles, simply follow me ;)</p><p>Next time, I will go through some more advanced synchronisations techniques that involves stateful Goroutines, Timers and Tickers.</p><p>See you in the next exploration :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c23c401c7b5" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/learning-go-in-2022-boost-your-journey-part-2-2c23c401c7b5">Learning go in 2022 — Boost your journey (part 2)</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning go in 2022 — Boost your journey (part 1)]]></title>
            <link>https://blog.devgenius.io/learning-go-in-2022-boost-your-journey-6edc606ed030?source=rss-76aa37aaa799------2</link>
            <guid isPermaLink="false">https://medium.com/p/6edc606ed030</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[getting-started]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alessandro Petraro]]></dc:creator>
            <pubDate>Tue, 26 Apr 2022 15:46:19 GMT</pubDate>
            <atom:updated>2023-01-26T09:41:30.812Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learning go — Boost your journey (part 1)</h3><p>I have been a Node.js developer for 5 years now, but during my developer career I have been always keen to learn new things and new technologies. <br>I will not explain here why learning go because I think out there is plenty of articles that are already doing a great job. I will try, instead, to help you embark in this journey to make your life easier :)</p><p>Every time I try to <strong>learn a new programming language</strong>, in fact, the question that I ask myself is always the same:<strong> where can I start to get a boost?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0sHw45SwHyIIHq8reHEG3Q.png" /><figcaption>credits to: <a href="https://github.com/MariaLetta/free-gophers-pack">https://github.com/MariaLetta/free-gophers-pack</a></figcaption></figure><h3>Getting started — Basic things first</h3><p>First of all, I needed to <strong>learn some syntax</strong> in order to be able to start reading and writing some Go code. After googling a little bit, I found what I was looking for: <a href="https://gobyexample.com/">go by example</a>. This website is really simple, but it has everything you need to get you started quickly. Here some of my take aways for a quick start on basic things:</p><ul><li>Use var to declare <strong>variables</strong>, use const to declare <strong>constants</strong>. <br>You can always <strong>declare</strong> a variable <strong>and assign</strong> it at the same time with the shortcut: a := 42</li><li>Go support for as the <strong>only loop construct</strong>, but it is really flexible and powerful. It in fact supports the following notations:<br>– Classic: for i := 0; i &lt; 3; i++ { ... } <br>– Single condition: for i &lt; 3 { ... i += 1 }<br>– No condition (infinite loop): for { ... } <br>In case of the single condition you must remember to increment the counter.</li><li>range construct can be useful to <strong>iterate over data structures</strong>. For example, given an array nums we could do something like for index, num := range nums { ... }). Range operator is also helpful for iterating over a map. For example, given a map myMap we could do something like: for key, value := range myMap { ... }</li><li><strong>Ternary</strong> are <strong>not supported</strong>, but we can still leverage on the classic if ... else</li><li>Main <a href="https://go.dev/tour/basics/11"><strong>primitive types</strong></a> in Go are: bool, string, int&amp; uint(16 - 32 - 64), float(32 - 64), complex(64 -128)</li><li>When something is not intialized in Go, it gets assigned the zero value (e.g. int, float-&gt; 0, string -&gt; “”, bool -&gt; false</li><li>As expected Go supports <strong>array</strong> (e.g.var a [5]int ) as a numbered sequence of elements of a <strong>specific length</strong>. <br>When working with data collections that may need to expand or contract, instead, <a href="https://gobyexample.com/slices"><strong>slices</strong></a> are the way to go. In order to create a slice you can simply do: s := make([]string, 3)</li><li>If you need a <strong>map</strong> you can simply do m := make(map[key] value) where key is the key type and value is your value type</li><li>Go supports <a href="https://gobyexample.com/closures"><strong>first class functions</strong></a> and for this you can for example create anonymous functions, return a function from a function, pass a function as callback and so on …</li></ul><h3>Struct</h3><p>Now, coming from a typescript context I started wondering, <strong>how can I create a class </strong>to make my code more structured?</p><p>Go is not an object oriented language (see <a href="https://go.dev/doc/faq#Is_Go_an_object-oriented_language">here</a> for more details) and for this <strong>there is no such a thing as class</strong>, but you can leverage on <strong>Struct</strong>. In Go a struct is a <strong>typed collection of fields.</strong></p><p>Let’s see how you can create a Rectangle in Go with a simple getArea method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a15c66123785db10fcb9d5587d7fe3d1/href">https://medium.com/media/a15c66123785db10fcb9d5587d7fe3d1/href</a></iframe><p>In the example above, we have that:</p><ol><li>Rectangle is a new type</li><li>getArea is a function that sets Rectangle as a <strong>Receiver</strong>. From now on, every Rectangle will be able to call the getArea method on itself. <br>For the ones of you that are coming from other languages like python or javascript, the Receiver r can be seen as the the same as self or this keyword.</li></ol><h3>Interfaces</h3><p>Now, <strong>what about interfaces?</strong> Go supports interfaces and in order to implement an interface, there is <strong>no implement keyword</strong> to be used. It is enough that whoever wants to implement it, <strong>simply defines all the needed methods.</strong></p><p>Let’s see how to create a simple Geometry interface and how to “implement” it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42443432bf593653c4fbef294d65bb71/href">https://medium.com/media/42443432bf593653c4fbef294d65bb71/href</a></iframe><p>Now that we have basic notions and we know how to make our code more structured, let’s jump to some important notions of the language:</p><ol><li>The Defer keyword</li><li>Pointers</li><li>Error VS Panic</li><li>Basic JSON handling</li></ol><h3>The Defer keyword</h3><p>The defer keyword is <strong>often</strong> used for <strong>cleanup purposes.</strong> Generally speaking, a defer statement <strong>defers the execution of a function until the surrounding function returns.</strong> The deferred call’s arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22dd8f2302631ba7798e0f9a49754b37/href">https://medium.com/media/22dd8f2302631ba7798e0f9a49754b37/href</a></iframe><h3>Pointers</h3><p>Go supports pointers allowing you to pass references to your values within your program. Pointers are a wide topic and should deserve an article by themselves, but in order to get started I tried to get my head around on some of the things I thought were important.</p><p>A pointer <strong>holds the memory address of a value. </strong>Its zero value in Go is nil</p><p>The syntax is pretty straightforward:</p><ol><li>Use * to dereference a pointer value</li><li>Use &amp; in order to get the address of a specific variable</li></ol><p>Let’s see a basic example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c238a6d3be2d5a4a671e4d779a01114a/href">https://medium.com/media/c238a6d3be2d5a4a671e4d779a01114a/href</a></iframe><p>Now, let’s clarify a common misconception. <strong>Supporting pointers does not mean that Go supports passing parameters by reference.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FRkzMtKbCKFUY3wYRMy%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fcbs-206-instinct-RkzMtKbCKFUY3wYRMy&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2FRkzMtKbCKFUY3wYRMy%2Fgiphy.gif%3Fcid%3D790b76119c9d4ebe2be934e352c65e72e1a7067b3f0c7adc%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6c9162aec8677cdae81cb9b11031c67/href">https://medium.com/media/a6c9162aec8677cdae81cb9b11031c67/href</a></iframe><p>In fact, <strong>in Go everything is passed by value</strong> and there is no such thing as pass by reference. This means that, every time we pass a parameter to a function, that param is copied over. You can only control if you want to <strong>pass a copy of the value</strong> <strong>or</strong> <strong>a copy of the reference to the value.</strong></p><p>In general, in Go every function argument is passed by value and by changing the argument value in the function body, the original value will not be affected. The only exceptions to this rule are<strong> slices</strong> and <strong>maps</strong>. They are still passed by value, but because they are <strong>reference types</strong>, any changes will change the underlying variable.</p><p>When to use a pointer and when not seems to be a hot topic in Go and for this I suggest you checking out <a href="https://github.com/golang/go/wiki/CodeReviewComments#receiver-type">this</a>.</p><h3>Error VS Panic</h3><p>In go by example we read that in Go it is idiomatic to communicate errors via an <strong>explicit, separate return value.</strong> By convention, <strong>errors are the last return value</strong> and have <strong>type error</strong>, a built-in interface.</p><p>For example: return -1, errors.New(&quot;Something went wrong&quot;)</p><p>A nil value in the error position indicates that there was <strong>no error.</strong></p><p>It’s also possible to use <strong>custom types as errors</strong> by implementing the Error() method on them.</p><p>Now, when should you use Panic instead? panic typically means something went <strong>unexpectedly wrong</strong>. Mostly it is used to fail fast on errors that shouldn’t occur during normal operation. For example: panic(&quot;Something really bad happened&quot;)</p><p><strong>In general, </strong>from my understanding, you should <strong>always</strong> <strong>prefer errors when possible.</strong></p><h3>JSON Handling</h3><p>Sooner or later we all have to handle some JSON. Coming from Node.js environment I was used to the classic JSON.stringify and JSON.parse methods. Go as well offers <strong>built-in support for JSON</strong> encoding and decoding, including to and from built-in and custom data type using the encoding/json package. Let’s dive into an example since it is worth million words:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9feefd6ec969745fea5ad8a5ccb0af3e/href">https://medium.com/media/9feefd6ec969745fea5ad8a5ccb0af3e/href</a></iframe><p>There are some important things to keep in mind:</p><ol><li>When encoding / decoding,<strong> only capitalised fields will be taken into account </strong>and for this they are called<strong> exported fields. </strong>Writing Message or message in the Response struct is then totally different since the latest one won’t be considered in encoding / decoding.</li><li>When <strong>encoding</strong>, if you used <strong>custom tags</strong> (see comments in the code above), Go will use those tags when encoding to JSON.</li><li>When <strong>decoding, </strong>if you used <strong>custom tags, </strong>Go will search for those in the JSON for the decoding.</li></ol><p>Keep in mind that it is also possible to stream JSON encodings directly to HTTP response bodies :)</p><h3>Conclusion</h3><p>This is only the start of the journey and obviously there is a lot more to be covered. Go was designed with concurrency in mind and for this my <strong>next exploration</strong> focus on <strong>Go Routines</strong> and <strong>Channels. </strong>If you are eager to read it, you can find it <a href="https://medium.com/@alessandropetraro/learning-go-in-2022-boost-your-journey-part-2-2c23c401c7b5">here</a> :)</p><p>If you enjoyed the article and you want to let me know, just leave me some claps 👏 and if you do not want to miss my next articles, simply follow me ;)</p><p>See you in the next exploration :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6edc606ed030" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/learning-go-in-2022-boost-your-journey-6edc606ed030">Learning go in 2022 — Boost your journey (part 1)</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>