<?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 Michał Łowicki on Medium]]></title>
        <description><![CDATA[Stories by Michał Łowicki on Medium]]></description>
        <link>https://medium.com/@mlowicki?source=rss-5b90d60d16b7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3fQyAyN3cY_zYqT2FDWFig.jpeg</url>
            <title>Stories by Michał Łowicki on Medium</title>
            <link>https://medium.com/@mlowicki?source=rss-5b90d60d16b7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 12 Apr 2026 18:14:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mlowicki/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[Untyped constants in Go]]></title>
            <link>https://medium.com/golangspec/untyped-constants-in-go-2c69eb519b5b?source=rss-5b90d60d16b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c69eb519b5b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Michał Łowicki]]></dc:creator>
            <pubDate>Thu, 19 Mar 2020 10:09:13 GMT</pubDate>
            <atom:updated>2020-03-19T10:09:13.553Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s start with quiz comparing two programs which differ only by single statement. Program <em>C</em> uses constant declaration (<a href="https://play.golang.org/p/V3huWMgQ3tJ">source code</a>):</p><pre>type N int</pre><pre>func main() {<br>    <strong>const c = 1</strong><br>    var n N = c<br>    fmt.Println(n)<br>}</pre><p>and program <em>V</em> uses variable declaration (<a href="https://play.golang.org/p/gvwIrlU9Ly4">source code</a>):</p><pre>type N int</pre><pre>func main() {<br>    <strong>var c = 1</strong><br>    var n N = c<br>    fmt.Println(n)<br>}</pre><p>Before scrolling down to see answers, please think for a moment about results of both <em>C</em> and <em>V</em> …</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>Program <em>C</em> writes to stdout 1. The second one (<em>V</em>) might be a small surprise. It doesn’t build at all and gives compile-time error: cannot use c (type int) as type N in assignment. If you would like to understand what is exactly happening then just keep reading and in 2 minutes you’ll get it.</p><p>Constants in Go can be either typed or untyped. Untyped are created when constant declaration doesn’t specify type (<a href="https://play.golang.org/p/6_Qfw29VUBN">source code</a>):</p><pre>const x float64 = 12<br>fmt.Printf(&quot;%T\n&quot;, x) // float64<br>const y = 12<br>fmt.Printf(&quot;%T\n&quot;, y) // int</pre><p>Constant y is untyped. When printing its type we’re getting int though…</p><blockquote><em>An untyped constant has a </em>default typ<em>e which is the type to which the constant is implicitly converted in contexts where a typed value is required.</em></blockquote><p>For example default type for integer constant is int or it’s float64 for floating-point number.</p><p>In program <em>V</em> variable c is being set to untyped constant expression 1. Default type of integer constant is int so type of c is ultimately set to int — implicit conversion happens because variables always need to have a type (<a href="https://play.golang.org/p/uc2id6qhjZw">source code</a>):</p><pre>var c = 1<br>fmt.Println(reflect.TypeOf(c).Name()) // int</pre><p>In program <em>V</em> while executing second assignment:</p><pre>var n N = c</pre><p>then assignability rules from language specification apply. Since n is of type N and c is of type int then we’ve a type mismatch and assignment statement is invalid. Why the program <em>C</em> works then? Because in that scenario c is an untyped constant and there is a dedicated assignability rule for such case:</p><blockquote><em>x</em> is assignable to <em>T if </em><em>x</em> is an untyped constant representable by a value of type <em>T.</em></blockquote><p>👏👏👏 below to help others discover this story. Please follow me here or on <a href="https://twitter.com/mlowicki">Twitter</a> if you want to get updates about new posts or boost work on future stories.</p><h4>Resources</h4><ul><li><a href="https://golang.org/ref/spec#Constants">https://golang.org/ref/spec#Constants</a></li><li><a href="https://golang.org/ref/spec#Assignability">https://golang.org/ref/spec#Assignability</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c69eb519b5b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/golangspec/untyped-constants-in-go-2c69eb519b5b">Untyped constants in Go</a> was originally published in <a href="https://medium.com/golangspec">golangspec</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pointer receiver methods and iteration variables]]></title>
            <link>https://medium.com/golangspec/pointer-receiver-methods-and-iteration-variables-f61ff53376cf?source=rss-5b90d60d16b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f61ff53376cf</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Michał Łowicki]]></dc:creator>
            <pubDate>Tue, 10 Mar 2020 23:20:54 GMT</pubDate>
            <atom:updated>2020-03-10T23:20:54.414Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0z_AFhrxzxLDkypHFEMfHg.jpeg" /></figure><h4>One more gotcha with re-using range clause variables.</h4><p>This story will start with a puzzle (<a href="https://play.golang.org/p/AIXKe6JZBI9">source code</a>):</p><pre>type T struct {<br>    name string<br>}</pre><pre>func (t T) M(wg *sync.WaitGroup) {<br>    fmt.Println(t.name)<br>    wg.Done()<br>}</pre><pre>func main() {<br>    var wg sync.WaitGroup<br>    for _, v := range []T{{&quot;foo&quot;}, {&quot;bar&quot;}, {&quot;baz&quot;}} {<br>        wg.Add(1)<br>        go v.M(&amp;wg)<br>    }<br>    wg.Wait()<br>}</pre><p>Think for a moment about what will be written to <em>stdout</em>? The answer is not that simple. It can be actually many different things. Program will always print foo, bar and baz, each in separate line but the order might be different each time:</p><pre>baz<br>foo<br>bar</pre><p>It’s really up to the scheduler how to run goroutines. Scheduler isn’t the topic of this post though. Let’s modify that program slightly to use a pointer receiver instead (<a href="https://play.golang.org/p/MVxfXni0l40">source code</a>):</p><pre>func (t *T) M(wg *sync.WaitGroup) {<br>    fmt.Println(t.name)<br>    wg.Done()<br>}</pre><p>It also depends on runtime’s scheduler but usually I get the same line three times:</p><pre>baz<br>baz<br>baz</pre><p>If you got intrigued why it differs from the first example then keep reading. This post will explain what is really happening here.</p><h4>defer vs go statements</h4><p>It’s worth to mention that we’ll get similar behaviour if we’ll replace <em>go statement</em> with <em>defer statement </em>(<a href="https://play.golang.org/p/1Ft46lSOCjT">source code</a>):</p><pre>type T struct {<br>    name string<br>}</pre><pre>func (t T) M() {<br>    fmt.Println(t.name)<br>}</pre><pre>func main() {<br>    for _, v := range []T{{&quot;foo&quot;}, {&quot;bar&quot;}, {&quot;baz&quot;}} {<br>        defer v.M()<br>    }<br>}</pre><p>Output:</p><pre>baz<br>bar<br>foo</pre><p>This is slightly different than code with <em>go</em> statement since output is deterministic — it doesn’t depend on the scheduler (deferred functions are called in LIFO order). If we’ll use pointer receiver then we’re also deterministic behaviour but outcome varies (<a href="https://play.golang.org/p/tkdS94WIJzb">source code</a>):</p><pre>type T struct {<br>    name string<br>}</pre><pre>func (t *T) M() {<br>    fmt.Println(t.name)<br>}</pre><pre>func main() {<br>    for _, v := range []T{{&quot;foo&quot;}, {&quot;bar&quot;}, {&quot;baz&quot;}} {<br>        defer v.M()<br>    }<br>}</pre><p>Output:</p><pre>baz<br>baz<br>baz</pre><p>It’s again the same line three times. To make our analysis slightly easier let’s focus on case with <em>defer statement</em> first since it gives deterministic behaviour.</p><p>Many people already know that loops and closures can be tricky (<a href="https://play.golang.org/p/9G0mJhwUu1V">source code</a>):</p><pre>for _, v := range []string{&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;} {<br>    defer func() {<br>        fmt.Println(v)<br>    }()<br>}</pre><p>Output:</p><pre>baz<br>baz<br>baz</pre><p>It isn’t anything specific to Golang. The same happens in other languages like JavaScript (<a href="https://jsfiddle.net/oj31rxhe/">source code</a>):</p><pre>(function() {<br>  var funcs = [];<br>  for (var v of [&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;]) {<br>    funcs.push(function() {<br>      console.info(v);<br>    });<br>  }<br>  funcs.forEach(f =&gt; f());<br>})();</pre><p>In browser console you’ll see baz logged 3 times. With<em> range clause </em>we need to be extra careful since in Go iteration variables are re-used for each iteration (<a href="https://play.golang.org/p/QiQ1zAt0Pv6">source code</a>):</p><pre>type T struct {<br>    name string<br>}</pre><pre>func main() {<br>    names := []T{{&quot;foo&quot;}, {&quot;bar&quot;}, {&quot;baz&quot;}}<br>    for _, name := range names {<br>        fmt.Printf(&quot;%p\n&quot;, &amp;name)<br>    }<br>}</pre><p>Output:</p><pre>0x40c138<br>0x40c138<br>0x40c138</pre><p>Now that we got a refresher on closures and intricacies of <em>range clause</em> variables, let’s move on to method calls.</p><pre>x.m()</pre><p>Such call is valid if method set of <em>x</em>’s type contains <em>m</em>. What is a <em>method se</em>t of arbitrary type <em>T</em>?</p><ul><li>Method set of <em>T</em> contains all methods with receiver type <em>T.</em></li><li>The method set of pointer type <em>*T</em> is the set of all methods declared with receiver <em>*T</em> or<em> T.</em></li></ul><p>Yes, there is asymmetry here. Language specification has additional rule:</p><pre>If x is addressable and &amp;x&#39;s method set contains m, x.m() is shorthand for (&amp;x).m():</pre><blockquote>For example map elements aren’t addressable — <a href="https://play.golang.org/p/isfZwRiIL2a">https://play.golang.org/p/isfZwRiIL2a</a>.</blockquote><p>This extra rule is relevant in our case. What it actually means? Let’s analyse snippet from above (<a href="https://play.golang.org/p/b0z9SNmjRyq">source code</a>):</p><pre>type T struct {<br>    name string<br>}</pre><pre>func (t *T) M() {<br>    fmt.Println(t.name)<br>}</pre><pre>func main() {<br>    for _, v := range []T{{&quot;foo&quot;}, {&quot;bar&quot;}, {&quot;baz&quot;}} {<br>        defer v.M()<br>    }<br>}</pre><p>It’s equivalent to:</p><pre>func main() {<br>    for _, v := range []T{{&quot;foo&quot;}, {&quot;bar&quot;}, {&quot;baz&quot;}} {<br>        defer (&amp;v).M()<br>    }<br>}</pre><p>Now it should be slightly clearer. In the examples where we see duplicated lines, methods on pointers to iterations variables are being called. Go doesn’t re-defines iteration variables — those are being re-used. Let’s add a bit more logging (<a href="https://play.golang.org/p/gW9lZKxIjIN">source code</a>):</p><pre>for _, v := range []T{{&quot;foo&quot;}, {&quot;bar&quot;}, {&quot;baz&quot;}} {<br>    fmt.Printf(&quot;%p\n&quot;, &amp;v)<br>    defer (&amp;v).M()<br> }</pre><p>Output:</p><pre>0x40c138<br>0x40c138<br>0x40c138<br>baz<br>baz<br>baz</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*BpgJOWPIMAAJRJyz5yhTsA.png" /><figcaption>State of memory after every iteration</figcaption></figure><p>Method is called on pointer and for every iteration we’re using the same pointer (referencing memory location of variable v). Deferred functions are fired after outer function finishes so v will be set to last element of slice — {&quot;baz&quot;}. This is why in stdout we see baz three times.</p><p>How is this different to the case when we’ve value receiver?</p><pre>type T struct {<br>    name string<br>}</pre><pre>func (t T) M() {<br>    fmt.Println(t.name)<br>}</pre><pre>func main() {<br>    for _, v := range []T{{&quot;foo&quot;}, {&quot;bar&quot;}, {&quot;baz&quot;}} {<br>        defer v.M()<br>    }<br>}</pre><p>Now we aren’t using pointers but deferring method on copy of each slice element — v contains copy of {&quot;foo&quot;} during first iteration, {&quot;bar&quot;} during 2nd iteration and so forth. This is why we don’t have duplicates.</p><p>Examples with <em>go statements</em> are pretty much the same. The only difference is that scheduler may run methods in different order than slice is being traversed.</p><p>👏👏👏 👏👏 below to help others discover this story. Please follow me here or on <a href="https://twitter.com/mlowicki">Twitter</a> if you want to get updates about new posts or boost work on future stories.</p><h4>Resources</h4><ul><li><a href="https://medium.com/golangspec/range-clause-and-the-address-of-iteration-variable-b1796885d2b7">https://medium.com/golangspec/range-clause-and-the-address-of-iteration-variable-b1796885d2b7</a></li><li><a href="https://golang.org/ref/spec#Go_statements">https://golang.org/ref/spec#Go_statements</a></li><li><a href="https://golang.org/ref/spec#Defer_statements">https://golang.org/ref/spec#Defer_statements</a></li><li><a href="https://golang.org/ref/spec#Calls">https://golang.org/ref/spec#Calls</a></li><li><a href="https://golang.org/ref/spec#Method_sets">https://golang.org/ref/spec#Method_sets</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f61ff53376cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/golangspec/pointer-receiver-methods-and-iteration-variables-f61ff53376cf">Pointer receiver methods and iteration variables</a> was originally published in <a href="https://medium.com/golangspec">golangspec</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Equality in Golang]]></title>
            <link>https://medium.com/golangspec/equality-in-golang-ff44da79b7f1?source=rss-5b90d60d16b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff44da79b7f1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Michał Łowicki]]></dc:creator>
            <pubDate>Wed, 26 Feb 2020 12:40:05 GMT</pubDate>
            <atom:updated>2020-02-26T12:40:05.952Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1yc4-cljb16qZ81Z9D9iWw.jpeg" /></figure><h4>Tale of comparison operators and {DeepEqual,Equal,EqualFold} methods</h4><p>You’ve probably seen == or != operators many times in .go files. It turns out that some types like e.g. maps or slices can’t be used as operands to these operators. It’s sometimes needed to compare such values though. In this post we’ll explore all rules behind equality operators in Go, how it plays with Unicode and what are the methods to compare non-comparable types.</p><p>Let’s start with something simple and actually not hiding many secrets. For booleans and numeric types (floats, integers, complex numbers) equality operators work without bigger surprises. Type float64 has few special values like <a href="https://golang.org/pkg/math/#NaN"><em>NaN</em></a><em> </em>(IEEE 754 “not a number” value), positive and negative infinity. It’s worth to mention that <em>NaN</em> is not equal to <em>NaN</em> (<a href="https://play.golang.org/p/_51rWkAY3Iw">source code</a>):</p><pre>nan := math.NaN()<br>pos_inf := math.Inf(1)<br>neg_inf := math.Inf(-1)<br>fmt.Println(nan == nan)         // false<br>fmt.Println(pos_inf == pos_inf) // true<br>fmt.Println(neg_inf == neg_inf) // true<br>fmt.Println(pos_inf == neg_inf) // false</pre><h4>Pointers</h4><p>Two pointers are equal if either both are <em>nil</em> or both point to exactly the same address in memory (<a href="https://play.golang.org/p/PVh75zZuhd8">source code</a>):</p><pre>var p1, p2 *string<br>name := &quot;foo&quot;<br>fmt.Println(p1 == p2) // true<br>p1 = &amp;name<br>p2 = &amp;name<br>fmt.Println(p1)       // 0x40c148<br>fmt.Println(p2)       // 0x40c148<br>fmt.Println(&amp;p1)      // 0x40c138<br>fmt.Println(&amp;p2)      // 0x40c140<br>fmt.Println(*p1)      // foo<br>fmt.Println(*p2)      // foo<br>fmt.Println(p1 == p2) // true</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*5CiGbw2Qy8YrHiayejtiGA.png" /></figure><p>Language spec also says:</p><blockquote>A struct or array type has size zero if it contains no fields (or elements, respectively) that have a size greater than zero. Two distinct zero-size variables may have the same address in memory.</blockquote><p>Let’s see that rule in action (<a href="https://play.golang.org/p/tie9qQ5j_oe">source code</a>):</p><pre>type S struct{}</pre><pre>func main() {<br>    var p1, p2 *S<br>    s1 := S{}<br>    s2 := S{}<br>    p1 = &amp;s1<br>    p2 = &amp;s2<br>    fmt.Printf(&quot;%p\n&quot;, p1) // 0x1e52bc<br>    fmt.Printf(&quot;%p\n&quot;, p2) // 0x1e52bc<br>    fmt.Println(p1)        // &amp;{}<br>    fmt.Println(p2)        // &amp;{}<br>    fmt.Println(&amp;p1)       // 0x40c138<br>    fmt.Println(&amp;p2)       // 0x40c140<br>    fmt.Println(*p1)       // {}<br>    fmt.Println(*p2)       // {}<br>    fmt.Println(p1 == p2)  // true<br>}</pre><p>By changing <em>S</em> type definition to non-empty struct like S struct {f int} you’ll see that <em>p1</em> and <em>p2</em> are not equal anymore — <a href="https://play.golang.org/p/VUV2cYYFiJ-">source code</a>.</p><h4>Channels</h4><p>With basic concurrency primitive in Go we’ve two rules i.e. two channels are equal when either:</p><ul><li>both are <em>nil</em></li><li>both are created by the same call to built-in function <em>make</em></li></ul><p>Code snippet above demonstrates this behaviour (<a href="https://play.golang.org/p/af843QMDBeh">source code</a>):</p><pre>func f(ch1 chan int, ch2 *chan int) {<br>    fmt.Println(ch1 == *ch2) // true<br>}</pre><pre>func main() {<br>    var ch1, ch2 chan int<br>    fmt.Println(ch1 == ch2) // true<br>    ch1 = make(chan int)<br>    ch2 = make(chan int)<br>    fmt.Println(ch1 == ch2) // false<br>    ch2 = ch1<br>    fmt.Printf(&quot;%p\n&quot;, &amp;ch1) // 0x40c138<br>    fmt.Printf(&quot;%p\n&quot;, &amp;ch2) // 0x40c140<br>    fmt.Println(ch1 == ch2)  // true<br>    f(ch1, &amp;ch1)<br>}</pre><h4>Interfaces</h4><p>First case might seem simple — two interface values are equal if both are <em>nil</em>. It’s important to remember when exactly interface value is <em>nil</em>. It happens when both dynamic type and dynamic value are <em>nil</em> (<a href="https://play.golang.org/p/MBhdC8z6OTy">source code</a>):</p><pre>type I interface{ m() }</pre><pre>type T []byte</pre><pre>func (t T) m() {}</pre><pre>func main() {<br>    var t T<br>    fmt.Println(t == nil) // true<br>    var i I = t<br>    fmt.Println(i == nil)                   // false<br>    fmt.Println(reflect.TypeOf(i))          // main.T<br>    fmt.Println(reflect.ValueOf(i).IsNil()) // true<br>}</pre><blockquote>More about interfaces in earlier series — <a href="https://medium.com/golangspec/interfaces-in-go-part-i-4ae53a97479c">https://medium.com/golangspec/interfaces-in-go-part-i-4ae53a97479c</a>.</blockquote><p>If dynamic types are identical and dynamic values are equal then two interface values are equal (<a href="https://play.golang.org/p/VqFxeov-ZoK">source code</a>):</p><pre>type A int<br>type B = A<br>type C int</pre><pre>type I interface{ m() }</pre><pre>func (a A) m() {}</pre><pre>func (c C) m() {}</pre><pre>func main() {<br>    var a I = A(1)<br>    var b I = B(1)<br>    var c I = C(1)<br>    fmt.Println(a == b) // true<br>    fmt.Println(b == c) // false<br>    fmt.Println(a == c) // false<br>}</pre><p>It’s possible to compare value <em>x</em> of non-interface type <em>X</em> with value <em>i</em> of interface type <em>I</em> . There are few limitations though:</p><ul><li>type <em>X</em> implements interface <em>I</em></li><li>type <em>X</em> is comparable</li></ul><p>If dynamic type of <em>i</em> is <em>X</em> and dynamic value of <em>i</em> is equal to <em>x</em> then values are equal (<a href="https://play.golang.org/p/qV_UhLdh6LZ">source code</a>):</p><pre>type I interface{ m() }</pre><pre>type X int</pre><pre>func (x X) m() {}</pre><pre>type Y int</pre><pre>func (y Y) m() {}</pre><pre>type Z int</pre><pre>func main() {<br>    var i I = X(1)<br>    fmt.Println(i == X(1)) // true<br>    fmt.Println(i == Y(1)) // false<br>    // fmt.Println(i == Z(1)) // mismatched types I and C<br>    // fmt.Println(i == 1) // mismatched types I and int<br>}</pre><p>If dynamic types of interface values are identical but not comparable then it will generate runtime panic (<a href="https://play.golang.org/p/VESFCGSQibF">source code</a>):</p><pre>type A []byte</pre><pre>func main() {<br>    var i interface{} = A{}<br>    var j interface{} = A{}<br>    fmt.Println(i == j)<br>}</pre><p>Output:</p><pre>panic: runtime error: comparing uncomparable type main.A</pre><p>If types are different but still not comparable then interface values aren’t equal (<a href="https://play.golang.org/p/Pnch0sNb47a">source code</a>):</p><pre>type A []byte<br>type B []byte</pre><pre>func main() {<br>    // A{} == A{} // slice can only be compared to nil<br>    var i interface{} = A{}<br>    var j interface{} = B{}<br>    fmt.Println(i == j) // false<br>}</pre><h4>Structs</h4><p>While comparing structs, corresponding non-blank fields are checked for equality — both exported and non-exported (<a href="https://play.golang.org/p/XZ5YUaTZmrx">source code</a>):</p><pre>type A struct {<br>    _ float64<br>    f1 int<br>    F2 string<br>}</pre><pre>type B struct {<br>    _ float64<br>    f1 int<br>    F2 string<br>}</pre><pre>func main() {<br>    fmt.Println(A{1.1, 2, &quot;x&quot;} == A{0.1, 2, &quot;x&quot;}) // true<br>    // fmt.Println(A{} == B{}) // mismatched types A and B <br>}</pre><p>It’s worth to introduce now main rule applicable not only for structs but all types:</p><blockquote>x == y <em>is allowed only when either </em>x<em> is assignable to </em>y<em> or </em>y<em> is assignable to </em>x<em>.</em></blockquote><p>This is why A{} == B{} above generates compile-time error.</p><h4>Arrays</h4><p>This is similar to struct explained earlier. Corresponding elements needs to be equal for the whole arrays to be equal (<a href="https://play.golang.org/p/puUHqu87vmv">source code</a>):</p><pre>type T struct {<br>    name string<br>    age int<br>    _ float64<br>}</pre><pre>func main() {<br>   x := [...]float64{1.1, 2, 3.14}<br>   fmt.Println(x == [...]float64{1.1, 2, 3.14}) // true<br>   y := [1]T{{&quot;foo&quot;, 1, 0}}<br>   fmt.Println(y == [1]T{{&quot;foo&quot;, 1, 1}}) // true<br>}</pre><h4>Strings</h4><p>Strings are in effect immutable slices of bytes and equality works for them by running comparison byte by byte (<a href="https://play.golang.org/p/pUku9ruapE6">source code</a>):</p><pre>fmt.Println(strings.ToUpper(&quot;ł&quot;) == &quot;Ł&quot;)     // true<br>fmt.Println(&quot;foo&quot; == &quot;foo&quot;)                  // true<br>fmt.Println(&quot;foo&quot; == &quot;FOO&quot;)                  // false<br>fmt.Println(&quot;Michał&quot; == &quot;Michal&quot;)            // false<br>fmt.Println(&quot;żondło&quot; == &quot;żondło&quot;)            // true<br>fmt.Println(&quot;żondło&quot; != &quot;żondło&quot;)            // false<br>fmt.Println(strings.EqualFold(&quot;ąĆź&quot;, &quot;ĄćŹ&quot;)) // true</pre><h4>Comparing something non-comparable</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*Vwg53G6Q6zRu_Caz5ppBmw.png" /><figcaption><a href="https://github.com/egonelbre">https://github.com/egonelbre</a></figcaption></figure><p>In this bucket we’ve three types: functions, maps and slices. We can’t do much about the functions. There is not way to compare them in Go (<a href="https://play.golang.org/p/fcQPTi-VcDX">source code</a>):</p><pre>f := func(int) int { return 1 }<br>g := func(int) int { return 2 }<br>f == g</pre><p>It generates compile-time error: invalid operation: f == g (func can only be compared to nil). It also gives a hint that we can compare functions to <em>nil</em>. The same is true for maps and slices (<a href="https://play.golang.org/p/PJppTEgadR2">source code</a>):</p><pre>f1 := func(int) int { return 1 }<br>m1 := make(map[int]int)<br>s1 := make([]byte, 10)<br>fmt.Println(f1 == nil) // false<br>fmt.Println(m1 == nil) // false<br>fmt.Println(s1 == nil) // false<br>var f2 func()<br>var m2 map[int]int<br>var s2 []byte<br>fmt.Println(f2 == nil) // true<br>fmt.Println(m2 == nil) // true<br>fmt.Println(s2 == nil) // true</pre><p>Are there any options for maps or slices though? Luckily there are and we’ll explore them right now…</p><h4>[]byte</h4><p>Package <a href="https://golang.org/pkg/bytes/">bytes</a> offers utilities to deal with byte slices and it provides functions to check if slices are equal and even equal under Unicode case-folding (<a href="https://play.golang.org/p/Dnusih61Xcc">source code</a>):</p><pre>s1 := []byte{&#39;f&#39;, &#39;o&#39;, &#39;o&#39;}<br>s2 := []byte{&#39;f&#39;, &#39;o&#39;, &#39;o&#39;}<br>fmt.Println(bytes.Equal(s1, s2)) // true<br>s2 = []byte{&#39;b&#39;, &#39;a&#39;, &#39;r&#39;}<br>fmt.Println(bytes.Equal(s1, s2)) // false<br>s2 = []byte{&#39;f&#39;, &#39;O&#39;, &#39;O&#39;}<br>fmt.Println(bytes.EqualFold(s1, s2)) // true<br>s1 = []byte(&quot;źdźbło&quot;)<br>s2 = []byte(&quot;źdŹbŁO&quot;)<br>fmt.Println(bytes.EqualFold(s1, s2)) // true<br>s1 = []byte{}<br>s2 = nil<br>fmt.Println(bytes.Equal(s1, s2)) // true</pre><p>What about maps or slices where elements of underlying arrays are not bytes? We’ve two options: <a href="https://golang.org/pkg/reflect/#DeepEqual">reflect.DeepEqual </a>, <a href="https://github.com/google/go-cmp">cmp</a> package or writing ad-hoc comparison code using e.g. <em>for</em> statement. Let’s see first two approaches in action.</p><h4>reflect.DeepEqual</h4><p>This function is generic method to compare any values:</p><pre>func DeepEqual(x, y interface{}) <a href="https://golang.org/pkg/builtin/#bool">bool</a></pre><p>Let’s see how it works with maps (<a href="https://play.golang.org/p/V_8OQT4MswR">source code</a>):</p><pre>m1 := map[string]int{&quot;foo&quot;: 1, &quot;bar&quot;: 2}<br>m2 := map[string]int{&quot;foo&quot;: 1, &quot;bar&quot;: 2}<br>// fmt.Println(m1 == m2) // map can only be compared to nil<br>fmt.Println(reflect.DeepEqual(m1, m2)) // true<br>m2 = map[string]int{&quot;foo&quot;: 1, &quot;bar&quot;: 3}<br>fmt.Println(reflect.DeepEqual(m1, m2)) // false<br>m3 := map[string]interface{}{&quot;foo&quot;: [2]int{1,2}}<br>m4 := map[string]interface{}{&quot;foo&quot;: [2]int{1,2}}<br>fmt.Println(reflect.DeepEqual(m3, m4)) // true<br>var m5 map[float64]string<br>fmt.Println(reflect.DeepEqual(m5, nil)) // false<br>fmt.Println(m5 == nil) // true</pre><p>and slices (<a href="https://play.golang.org/p/6rHBsJcB54A">source code</a>):</p><pre>s := []string{&quot;foo&quot;}<br>fmt.Println(reflect.DeepEqual(s, []string{&quot;foo&quot;})) // true<br>fmt.Println(reflect.DeepEqual(s, []string{&quot;bar&quot;})) // false<br>s = nil<br>fmt.Println(reflect.DeepEqual(s, []string{})) // false<br>s = []string{}<br>fmt.Println(reflect.DeepEqual(s, []string{})) // true</pre><p>You can even apply it to types covered earlier like structs (<a href="https://play.golang.org/p/BZo1HxwxVJ9">source code</a>):</p><pre>type T struct {<br>    name string<br>    Age  int<br>}</pre><pre>func main() {<br>    t := T{&quot;foo&quot;, 10}<br>    fmt.Println(reflect.DeepEqual(t, T{&quot;bar&quot;, 20})) // false<br>    fmt.Println(reflect.DeepEqual(t, T{&quot;bar&quot;, 10})) // false<br>    fmt.Println(reflect.DeepEqual(t, T{&quot;foo&quot;, 10})) // true<br>}</pre><h4>cmp package</h4><p>Package <em>cmp</em> offers additional capabilities like customisable <em>Equal</em> methods , option to ignore non-exported struct fields or get diff of two values (source code):</p><pre>import (<br>    &quot;fmt&quot;</pre><pre>    &quot;github.com/google/go-cmp/cmp&quot;<br>)</pre><pre>type T struct {<br>    Name string<br>    Age  int<br>    City string<br>}</pre><pre>func main() {<br>    x := T{&quot;Michał&quot;, 99, &quot;London&quot;}<br>    y := T{&quot;Adam&quot;, 88, &quot;London&quot;}<br>    if diff := cmp.Diff(x, y); diff != &quot;&quot; {<br>        fmt.Println(diff)<br>    }<br>}</pre><p>Output:</p><pre>  main.T{<br>-       Name: &quot;Michał&quot;,<br>+       Name: &quot;Adam&quot;,<br>-       Age:  99,<br>+       Age:  88,<br>        City: &quot;London&quot;,<br>  }</pre><p>Please check <a href="https://github.com/google/go-cmp">documentation</a> out to learn more.</p><h4>Timing attacks</h4><p>To prevent <a href="https://en.wikipedia.org/wiki/Timing_attack">timing attacks</a> there’s a standard package with function where time to compare slices is independent of the parameters’ content.</p><pre>import (<br>    &quot;bytes&quot;<br>    &quot;crypto/subtle&quot;<br>    &quot;testing&quot;<br>)</pre><pre>var (<br>    x = []byte{&#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;}<br>    y = []byte{&#39;b&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;}<br>    z = []byte{&#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;b&#39;}<br>)</pre><pre>func BenchmarkBytesEqualXY(b *testing.B) {<br>    for n := 0; n &lt; b.N; n++ {<br>        bytes.Equal(x, y)<br>    }<br>}</pre><pre>func BenchmarkBytesEqualXZ(b *testing.B) {<br>    for n := 0; n &lt; b.N; n++ {<br>        bytes.Equal(x, z)<br>    }<br>}</pre><pre>func BenchmarkConstTimeCompXY(b *testing.B) {<br>    for n := 0; n &lt; b.N; n++ {<br>        subtle.ConstantTimeCompare(x, y)<br>    }<br>}</pre><pre>func BenchmarkConstTimeCompXZ(b *testing.B) {<br>    for n := 0; n &lt; b.N; n++ {<br>        subtle.ConstantTimeCompare(x, z)<br>    }<br>}</pre><pre>$ go test -bench=.<br>goos: darwin<br>goarch: amd64<br>pkg: github.com/mlowicki/subtle<br>BenchmarkBytesEqualXY-12        554047392          2.09 ns/op<br>BenchmarkBytesEqualXZ-12        274583632          4.38 ns/op<br>BenchmarkConstTimeCompXY-12     66717505           15.0 ns/op<br>BenchmarkConstTimeCompXZ-12     70632979           15.6 ns/op</pre><p>Time to compare <em>x</em> and <em>y</em> using <em>bytes.Equal</em> is doubled compared to <em>x</em> and <em>z </em>so it clearly depends on the content of parameters as length is always the same in tests above<em>. </em>That difference is negligible when using <em>subtle.ConstantTimeCompare</em>.</p><p>👏👏👏 below to help others discover this story. Please follow me here or on <a href="https://twitter.com/mlowicki">Twitter</a> if you want to get updates about new posts or boost work on future stories.</p><h4>Resources</h4><ul><li><a href="https://golang.org/ref/spec#Comparison_operators">https://golang.org/ref/spec#Comparison_operators</a></li><li><a href="https://medium.com/golangspec/interfaces-in-go-part-i-4ae53a97479c">https://medium.com/golangspec/interfaces-in-go-part-i-4ae53a97479c</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff44da79b7f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/golangspec/equality-in-golang-ff44da79b7f1">Equality in Golang</a> was originally published in <a href="https://medium.com/golangspec">golangspec</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Defer statement in Golang (part I)]]></title>
            <link>https://medium.com/golangspec/defer-statement-in-golang-part-i-8e658a2ea49a?source=rss-5b90d60d16b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e658a2ea49a</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Michał Łowicki]]></dc:creator>
            <pubDate>Sun, 02 Feb 2020 18:13:33 GMT</pubDate>
            <atom:updated>2020-02-02T18:14:24.121Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNQwcv_BR30ugL-OyQHYmw.jpeg" /></figure><p>Deferred function is declared inside another function and is called when surrounding function exits — either normally or if goroutine panics. This mechanism is used e.g. to do cleanup and close open files or sockets.</p><p>Deferred functions are evaluated in LIFO fashion (<a href="https://play.golang.org/p/-k97LqnHLZl">source code</a>):</p><pre>func f() {<br>    fmt.Println(&quot;f()&quot;)<br>}</pre><pre>func g() {<br>    fmt.Println(&quot;g()&quot;)<br>}</pre><pre>func h() {<br>    fmt.Println(&quot;h()&quot;)<br>}</pre><pre>func main() {<br>    defer f()<br>    defer g()<br>    defer h()<br>}</pre><p>Output:</p><pre>h()<br>g()<br>f()</pre><p><em>defer</em> statement can be used anywhere inside the function so it’s not limited only to its beginning (<a href="https://play.golang.org/p/45VQ9_U0acE">source code</a>):</p><pre>func f() {<br>    fmt.Println(&quot;boo&quot;)<br>}</pre><pre>func main() {<br>    fmt.Println(&quot;one&quot;)<br>    defer f()<br>    fmt.Println(&quot;two&quot;)<br>}</pre><p>Output:</p><pre>one<br>two<br>boo</pre><h4>Anonymous functions</h4><p>It’s allowed to used both, named and anonymous functions with <em>defer</em> statement (<a href="https://play.golang.org/p/45VQ9_U0acE">source code</a>):</p><pre>func main() {<br>     defer func() {<br>         fmt.Println(&quot;foo&quot;)<br>     }()<br>}</pre><p>Output is foo.</p><h4>Evaluating deferred function</h4><p>When deferred function is <em>nil</em> then runtime error is thrown but it’s done when outer function exists not at the moment statement is executed (<a href="https://play.golang.org/p/07HYBN5Y-37">source code</a>):</p><pre>func main() {<br>    var f func()<br>    defer f()<br>    fmt.Println(&quot;foo&quot;)<br>}</pre><p>Output:</p><pre>foo<br>panic: runtime error: invalid memory address or nil pointer dereference<br>[signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0x8d034]</pre><pre>goroutine 1 [running]:<br>main.main()<br>	/tmp/sandbox581176742/prog.go:11 +0xdb</pre><p>(11th line is the closing bracket of <em>main</em> function)</p><p>Function used by <em>defer</em> statement is evaluated at the moment statement is encountered, not when surrounding function exists (<a href="https://play.golang.org/p/e-whzfC9RvW">source code</a>):</p><pre>func main() {<br>    var f func()<br>    defer f()<br>    f = func() {<br>        fmt.Println(&quot;foo&quot;)<br>    }<br>}</pre><p>Output:</p><pre>panic: runtime error: invalid memory address or nil pointer dereference<br>[signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0x8ce94]<br><br>goroutine 1 [running]:<br>main.main()<br>	/tmp/sandbox806328181/prog.go:13 +0x7b</pre><h4>Evaluating parameters of deferred function</h4><p>While processing <em>defer</em> statement arguments are evaluated. Those arguments will be used when outer function exists (<a href="https://play.golang.org/p/k4KeV2xOLvr">source code</a>):</p><pre>func g() int {<br>    fmt.Println(&quot;g()&quot;)<br>    return 0<br>}</pre><pre>func f(int) {<br>    fmt.Println(&quot;f()&quot;)<br>}</pre><pre>func main() {<br>    defer f(g())<br>    fmt.Println(&quot;Hello world!&quot;)<br>}</pre><p>Output:</p><pre>g()<br>Hello world!<br>f()</pre><p>If array is passed and modified before outer function exists then original (at the moment of <em>defer</em> statement) value will be used (<a href="https://play.golang.org/p/Kjpapy9yGxT">source code</a>):</p><pre>func f(nums [4]int) {<br>    fmt.Printf(&quot;%v\n&quot;, nums)<br>}</pre><pre>func main() {<br>    nums := [...]int{0,1,2,3}<br>    defer f(nums)<br>    nums[0] += 1<br>}</pre><p>Output is [0 1 2 3].</p><p>If we’ll use type which is a descriptor like slice then modified arguments will be used (<a href="https://play.golang.org/p/4I7cPyPtbNf">source code</a>):</p><pre>func f(nums []int) {<br>    fmt.Printf(&quot;%v\n&quot;, nums)<br>}</pre><pre>func main() {<br>    nums := []int{0,1,2,3}<br>    defer f(nums)<br>    nums[0] += 1<br>}</pre><p>Output is [1 1 2 3]. The same is true for e.g. maps (<a href="https://play.golang.org/p/cY4GE1gH3qB">source code</a>):</p><pre>func f(nums map[string]int) {<br>    fmt.Printf(&quot;%v\n&quot;, nums)<br>}</pre><pre>func main() {<br>    nums := map[string]int{&quot;one&quot;: 1}<br>    defer f(nums)<br>    nums[&quot;one&quot;] += 1<br>}</pre><p>Output is map[one:2].</p><h4>Changing return value(s) of surrounding function</h4><p>If outer function has named result value(s) then deferred function has access to it through closure and can modify it (<a href="https://play.golang.org/p/abPUcpFfbnF">source code</a>):</p><pre>func f() (v int) {<br>    defer func() {<br>        v *= 2<br>    }()<br>    v = 2<br>    return<br>}<br><br>func main() {<br>    fmt.Println(f())<br>}</pre><p>Output is 4.</p><h4>Return value(s) of deferred function</h4><p>Whatever deferred function returns is discarded (<a href="https://play.golang.org/p/zkjT_THr40Q">source code</a>):</p><pre>func f() int {<br>    defer func() int {<br>        return 5<br>    }()<br>    return 0<br>}<br> <br>func main() {<br>    fmt.Println(f())<br>}</pre><p>Output is 0.</p><h4>Resources</h4><p><a href="https://golang.org/ref/spec#Defer_statements">The Go Programming Language Specification</a></p><p>In 2nd part we’ll discuss handling panics, common uses cases of <em>defer</em> statement and performance of deferred functions. Stay tuned.</p><p>👏👏👏 below to help others discover this story. Please follow me here or on <a href="https://twitter.com/mlowicki">Twitter</a> if you want to get updates about new posts or boost work on future stories.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e658a2ea49a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/golangspec/defer-statement-in-golang-part-i-8e658a2ea49a">Defer statement in Golang (part I)</a> was originally published in <a href="https://medium.com/golangspec">golangspec</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“for” statement and its all faces in Golang]]></title>
            <link>https://medium.com/golangspec/for-statement-and-its-all-faces-in-golang-abcbdc011f81?source=rss-5b90d60d16b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/abcbdc011f81</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Michał Łowicki]]></dc:creator>
            <pubDate>Wed, 15 Jan 2020 03:06:51 GMT</pubDate>
            <atom:updated>2020-01-17T13:46:47.891Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dsDbWPneFC-2G_lQOUBUIg.jpeg" /></figure><p>In contrast to many other languages, Go doesn’t have multiple constructs for executing block of code repeatedly. There’s single statement (<em>for</em> statement) which takes different forms to support various scenarios and also integrates well with Go-specific mechanisms like slices or channels. In this post we’ll examine under a microscope something which is more interesting than it may seem at first glance.</p><h4>1. Single boolean condition</h4><p>Let’s start with the simplest form where only optional bool condition is in use (<a href="https://play.golang.org/p/3S28T56Q9AG">source code</a>):</p><pre>var v int = 39<br>for v != 0 {<br>     fmt.Println(v)<br>     if v &gt; 16 {<br>         v /= 4<br>     } else {<br>         v /= 2<br>     }<br>}</pre><p>Output:</p><pre>39<br>9<br>4<br>2<br>1</pre><p>It’s pretty straightforward so the result shouldn’t be any surprise. Delicate modification unveils rule which must be followed by conditions used inside <em>for</em> statements (<a href="https://play.golang.org/p/qtCRWk8qmDP">source code</a>):</p><pre>var v int = 39<br>for v {<br>    fmt.Println(v)<br>    if v &gt; 16 {<br>        v /= 4<br>    } else {<br>        v /= 2<br>    }<br>}</pre><p>Such program doesn’t compile. It’s required to use boolean condition:</p><pre>non-bool v (type int) used as for condition</pre><blockquote><em>Condition is checked before each loop so if it evaluates to </em>false<em> immediately, block isn’t executed even once.</em></blockquote><p>It’s legal to omit condition completely and then it’s equivalent to boolean value <em>true</em>:</p><pre>package main</pre><pre>import (<br>    &quot;net/http&quot;<br>    &quot;time&quot;<br>)</pre><pre>func main() {<br>    for {<br>        resp, err := http.Get(&quot;<a href="https://facebook.com">https://facebook.com</a>&quot;)<br>        if err != nil {<br>            time.Sleep(time.Second)<br>        }<br>        defer resp.Body.Close()<br>        break<br>    }<br>}</pre><h4>2. “For” clause</h4><p>This is the form, most coders are familiar with. It’s an extension to previous one. It adds <em>init</em> and <em>post</em> statements (<a href="https://play.golang.org/p/4sgL67gpCBh">source code</a>):</p><pre>for i := 0; i &lt; 5; i++ {<br>    fmt.Println(i)<br>}</pre><p>Output:</p><pre>0<br>1<br>2<br>3<br>4</pre><p><em>Init</em> statement ( i := 0) is executed only once before evaluating condition for the very first time. We can omit this statement if needed (source code):</p><pre>i := 0<br>for ; i &lt; 5; i++ {<br>    fmt.Println(i)<br>}</pre><p>Output:</p><pre>0<br>1<br>2<br>3<br>4</pre><p>Semicolon before condition is required. What can be used as <em>init</em> statement?</p><ul><li>short variable declaration</li><li>assignment</li><li>increment / decrement statement</li><li>send statement (<a href="https://play.golang.org/p/ywS_KhTODYi">source code</a>):</li></ul><pre>ch := make(chan int, 1)<br>i := 0<br>for ch &lt;- 1; i &lt; 5; i++ {<br>    fmt.Println(i)<br>}</pre><ul><li>expression statement like e.g. function call (<a href="https://play.golang.org/p/ATsQzHNdkIN">source code</a>):</li></ul><pre>i := 0<br>for fmt.Println(&quot;start&quot;); i &lt; 5; i++ {<br>    fmt.Println(i)<br>}</pre><p><em>Post</em> statement is executed each time block inside <em>for</em> statement is executed (<a href="https://play.golang.org/p/Xl1VhEJ5Rgt">source code</a>):</p><pre>for i := 0; i &lt; 5; fmt.Println(&quot;after&quot;) {<br>    fmt.Println(i)<br>    i++<br>}</pre><p>Output:</p><pre>0<br>after<br>1<br>after<br>2<br>after<br>3<br>after<br>4<br>after</pre><pre>for i := 0; i &lt; 5; fmt.Println(&quot;after&quot;) {<br>    i++<br>    break<br>}</pre><p>This program doesn’t print anything (<a href="https://play.golang.org/p/j59fSXjr5uE">source code</a>) because of <em>break</em> statement but it’s different story when <em>continue</em> statement is in use (<a href="https://play.golang.org/p/-XZ_cOTDhF8">source code</a>):</p><pre>for i := 0; i &lt; 5; fmt.Println(&quot;after&quot;) {<br>    i++<br>    continue<br> }</pre><p>Output:</p><pre>after<br>after<br>after<br>after<br>after</pre><p>The same rules apply to <em>post</em> statement but with one exception — short variable declaration is not possible there (<a href="https://play.golang.org/p/o6IybDDyYag">source code</a>):</p><pre>for i := 0; i &lt; 5; j := 0 {<br>    fmt.Println(i)<br>    i++<br>}</pre><p>Such code doesn’t compile and gives:</p><pre>syntax error: cannot declare in post statement of for loop</pre><p>Post statement can be omitted but semicolon after condition is then required (<a href="https://play.golang.org/p/ptaMOIZ1lP7">source code</a>):</p><pre>for i := 0; i &lt; 5; {<br>    fmt.Println(i)<br>    i++<br>}</pre><p>Output:</p><pre>0<br>1<br>2<br>3<br>4</pre><h4>3. “Range” clause</h4><p>This variant allows to iterate through array, pointer to array, slice, string, map or values received on a channel. Let’s go through all types to observe all nuances.</p><h4>slice</h4><p>Basic use cases are pretty obvious (<a href="https://play.golang.org/p/s1KjRKNDBJ5">source code</a>):</p><pre>nums := []string{&quot;one&quot;, &quot;two&quot;, &quot;three&quot;}<br>for idx, num := range nums {<br>    fmt.Printf(&quot;%d: %s\n&quot;, idx, num)<br>}<br>for idx := range nums {<br>   fmt.Println(idx)<br>}<br>for range nums {<br>   fmt.Println(&quot;tick&quot;)<br>}</pre><p>Output:</p><pre>0: one<br>1: two<br>2: three<br>0<br>1<br>2<br>tick<br>tick<br>tick</pre><p>It’s worth to note that assigning different slice to a variable won’t change iterations (<a href="https://play.golang.org/p/wHCRcYL_K9t">source code</a>):</p><pre>a := []string{&quot;one&quot;, &quot;two&quot;, &quot;three&quot;, &quot;four&quot;, &quot;five&quot;}<br>b := a[:3]<br>for idx, num := range b {<br>    b = b[:5]<br>    fmt.Printf(&quot;%d: %s\n&quot;, idx, num)<br>}</pre><p>Output:</p><pre>0: one<br>1: two<br>2: three</pre><p>It’s possible though to change values of slice’s element during iterations and this will be visible if respective iteration entry hasn’t been created yet (<a href="https://play.golang.org/p/n5qF7yEh_i_A">source code</a>):</p><pre>a := []string{&quot;one&quot;, &quot;two&quot;, &quot;three&quot;, &quot;four&quot;, &quot;five&quot;}<br>for idx, num := range a {<br>    a[4] = &quot;six&quot;<br>    fmt.Printf(&quot;%d: %s\n&quot;, idx, num)<br>}</pre><p>Output:</p><pre>0: one<br>1: two<br>2: three<br>3: four<br>4: six</pre><blockquote><em>No iterations will be created for </em>nil<em> slice.</em></blockquote><h4>array</h4><p>Usage and behaviour is similar to slice (<a href="https://play.golang.org/p/RooKdadsWpq">source code</a>):</p><pre>nums := [...]string{&quot;one&quot;, &quot;two&quot;, &quot;three&quot;}<br>for idx, num := range nums {<br>    fmt.Printf(&quot;%d: %s\n&quot;, idx, num)<br>}<br>for idx := range nums {<br>    fmt.Println(idx)<br>}<br>for range nums {<br>    fmt.Println(&quot;tick&quot;)<br>}</pre><p>Output:</p><pre>0: one<br>1: two<br>2: three<br>0<br>1<br>2<br>tick<br>tick<br>tick</pre><p>Changing the content of array won’t be reflected when <em>for</em> loop already started (<a href="https://play.golang.org/p/jCPPHDr5F3b">source code</a>):</p><pre>a := [...]string{&quot;one&quot;, &quot;two&quot;, &quot;three&quot;, &quot;four&quot;, &quot;five&quot;}<br>for idx, num := range a {<br>    a[4] = &quot;six&quot;<br>    fmt.Printf(&quot;%d: %s\n&quot;, idx, num)<br>}</pre><p>Output:</p><pre>0: one<br>1: two<br>2: three<br>3: four<br>4: five</pre><p>It’ll be reflected though if at most one iteration variable will be used (<a href="https://play.golang.org/p/HSpoX2MuGD9">source code</a>):</p><pre>a := [...]string{&quot;one&quot;, &quot;two&quot;, &quot;three&quot;, &quot;four&quot;, &quot;five&quot;}<br>for idx := range a {<br>    a[4] = &quot;six&quot;<br>    fmt.Printf(&quot;%d: %s\n&quot;, idx, a[idx])<br>}</pre><p>Output:</p><pre>0: one<br>1: two<br>2: three<br>3: four<br>4: six</pre><h4>pointer to array</h4><p>This is almost identical to pure array (<a href="https://play.golang.org/p/RZy92AT8KkE">source code</a>):</p><pre>nums := &amp;[...]string{&quot;one&quot;, &quot;two&quot;, &quot;three&quot;}<br>for idx, num := range *nums {<br>    fmt.Printf(&quot;%d: %s\n&quot;, idx, num)<br>}<br>for idx, num := range nums {<br>    fmt.Printf(&quot;%d: %s\n&quot;, idx, num)<br>}<br>for idx := range nums {<br>    fmt.Println(idx)<br>}<br>for range nums {<br>   fmt.Println(&quot;tick&quot;)<br>}</pre><p>Output:</p><pre>0: one<br>1: two<br>2: three<br>0: one<br>1: two<br>2: three<br>0<br>1<br>2<br>tick<br>tick<br>tick</pre><p>The difference is with changing value of array’s elements which will be visible in loop which has already started even if two iteration variables will be used (<a href="https://play.golang.org/p/XjjiGdNbJ9X">source code</a>):</p><pre>a := &amp;[...]string{&quot;one&quot;, &quot;two&quot;, &quot;three&quot;, &quot;four&quot;, &quot;five&quot;}<br>for idx, num := range a {<br>    a[4] = &quot;six&quot;<br>    fmt.Printf(&quot;%d: %s\n&quot;, idx, num)<br>}</pre><p>Output:</p><pre>0: one<br>1: two<br>2: three<br>3: four<br>4: six</pre><h4>string</h4><p>We’ll explore this scenario with string containing non-ASCII characters (<a href="https://play.golang.org/p/UuQ-gMZbkU7">source code</a>):</p><pre>s := &quot;żądło&quot;<br>for i := 0; i &lt; len(s); i++ {<br>    fmt.Printf(&quot;%q\n&quot;, s[i])<br>}<br>fmt.Println(strings.Repeat(&quot;*&quot;, 10))<br>for i, c := range s {<br>    fmt.Printf(&quot;%d: %q\n&quot;, i, c)<br>}</pre><p>Output:</p><pre>&#39;Å&#39;<br>&#39;¼&#39;<br>&#39;Ä&#39;<br>&#39;\u0085&#39;<br>&#39;d&#39;<br>&#39;Å&#39;<br>&#39;\u0082&#39;<br>&#39;o&#39;<br>**********<br>0: &#39;ż&#39;<br>2: &#39;ą&#39;<br>4: &#39;d&#39;<br>5: &#39;ł&#39;<br>7: &#39;o&#39;</pre><p>How to interpret above result? Using built-in <em>len</em> function, loop iterates over each byte within a string. The second <em>for</em> statement goes through Unicode code points, encoded as UTF-8. Index value points to index of first byte of the current code point.</p><p>If only one iteration variable is present then it’ll be assigned to index iteration value — index of first byte of current code point (<a href="https://play.golang.org/p/ZUsEpa8hDER">source code</a>):</p><pre>s := &quot;żądło&quot;<br>for i := range s {<br>    fmt.Printf(&quot;%d\n&quot;, i)<br>}</pre><p>Output:</p><pre>0<br>2<br>4<br>5<br>7</pre><h4>map</h4><p>Let’s begin with few basic examples (<a href="https://play.golang.org/p/ljquOGNu57S">source code</a>):</p><pre>m := map[string]int{&quot;one&quot;: 1, &quot;two&quot;: 2, &quot;three&quot;: 3}<br>for range m {<br>     fmt.Println(&quot;loop&quot;)<br>}<br>for k := range m {<br>     fmt.Printf(&quot;key: %q\n&quot;, k)<br>}<br>for k, v := range m {<br>     fmt.Printf(&quot;key: %q, value: %d\n&quot;, k, v)<br>}</pre><p>Output:</p><pre>loop<br>loop<br>loop<br>key: &quot;one&quot;<br>key: &quot;two&quot;<br>key: &quot;three&quot;<br>key: &quot;one&quot;, value: 1<br>key: &quot;two&quot;, value: 2<br>key: &quot;three&quot;, value: 3</pre><p>Idiomatic code skips iteration variable instead of using blank identifier (<a href="https://play.golang.org/p/rTqacf7TtLA">source code</a>):</p><pre>m := map[string]int{&quot;one&quot;: 1, &quot;two&quot;: 2, &quot;three&quot;: 3}<br>for range m { // idiomatic<br>    fmt.Println(&quot;a&quot;)<br>}<br>for _ = range m {<br>    fmt.Println(&quot;b&quot;)<br>}<br>for _, _ = range m {<br>    fmt.Println(&quot;c&quot;)<br>}<br>for k := range m { // idiomatic<br>    fmt.Printf(&quot;key: %q\n&quot;, k)<br>}<br>for k, _ := range m {<br>    fmt.Printf(&quot;key: %q\n&quot;, k)<br>}</pre><p>Output:</p><pre>a<br>a<br>a<br>b<br>b<br>b<br>c<br>c<br>c<br>key: &quot;two&quot;<br>key: &quot;three&quot;<br>key: &quot;one&quot;<br>key: &quot;one&quot;<br>key: &quot;two&quot;<br>key: &quot;three&quot;</pre><p>There’re none iterations over <em>nil</em> map (<a href="https://play.golang.org/p/E_1csw866yT">source code</a>):</p><pre>var m map[string]int<br>for range m {<br>    fmt.Println(&quot;foo&quot;)<br>}<br>m = map[string]int{&quot;one&quot;: 1, &quot;two&quot;: 2}<br>for range m {<br>    fmt.Println(&quot;bar&quot;)<br>}</pre><p>Output:</p><pre>bar<br>bar</pre><p>Map is a mutable data structure so while iterating, its content may change by adding / removing keys or changing values associated with keys. If key has been added while going over map then specification says it’s undefined behaviour if iteration for that key will be created — will be either skipped or processed (<a href="https://play.golang.org/p/vJeidX7qlUp">source code</a>):</p><pre>m := make(map[string]int)<br>m[&quot;one&quot;] = 1<br>m[&quot;two&quot;] = 2<br>for k := range m {<br>    fmt.Println(k)<br>    m[&quot;four&quot;] = 4<br>}</pre><p>Such program will always print one and two (order is not defined). It’s undefined though if also four will be written to stdout.</p><p>It’s guaranteed by spec that if key for which iteration value hasn’t been produced yet will be removed then such key won’t be produced (<a href="https://play.golang.org/p/B1aesE3s-K7">source code</a>):</p><pre>m := make(map[string]int)<br>m[&quot;one&quot;] = 1<br>m[&quot;two&quot;] = 2<br>for k := range m {<br>    fmt.Println(k)<br>    delete(m, &quot;two&quot;)<br>}</pre><p>If the first iteration value will be “one” then it’s guaranteed that second iteration won’t happen.</p><p>Changes to map’s values will be reflected in already running loop (<a href="https://play.golang.org/p/N_UIaeEc570">source code</a>):</p><pre>nums := map[string]int{&quot;one&quot;: 1, &quot;two&quot;: 2}<br>for idx, num := range nums {<br>    fmt.Printf(&quot;%s: %d\n&quot;, idx, num)<br>    nums[&quot;one&quot;] = 11<br>    nums[&quot;two&quot;] = 22<br>}<br>nums = map[string]int{&quot;one&quot;: 1, &quot;two&quot;: 2}<br>for idx := range nums {<br>    fmt.Printf(&quot;%s: %d\n&quot;, idx, nums[idx])<br>    nums[&quot;one&quot;] = 11<br>    nums[&quot;two&quot;] = 22<br>}</pre><p>Output depends on the order of how keys will be processed but in any way, the second iteration will show updated value like:</p><pre>one: 1<br>two: 22<br>two: 2<br>one: 11</pre><h4>channel</h4><p>Range clause with channel iterates over all values sent to channel until that channel is closed (<a href="https://play.golang.org/p/o6r2sL4v9jr">source code</a>):</p><pre>ch := make(chan int)<br>go func() {<br>    time.Sleep(3 * time.Second)<br>    ch &lt;- 1<br>    time.Sleep(2 * time.Second)<br>    ch &lt;- 2<br>    time.Sleep(time.Second)<br>    close(ch)<br>}()<br>fmt.Printf(&quot;before:\t\t%s\n&quot;, time.Now())<br>for v := range ch {<br>    fmt.Printf(&quot;tick #%d:\t%s\n&quot;, v, time.Now())<br>}<br>fmt.Printf(&quot;after:\t\t%s\n&quot;, time.Now())</pre><p>Output:</p><pre>before:		2009-11-10 23:00:00 +0000 UTC m=+0.000000001<br>tick #1:	2009-11-10 23:00:03 +0000 UTC m=+3.000000001<br>tick #2:	2009-11-10 23:00:05 +0000 UTC m=+5.000000001<br>after:		2009-11-10 23:00:06 +0000 UTC m=+6.000000001</pre><p>If nothing has been sent for already closed channel then no iterations will be executed (<a href="https://play.golang.org/p/UaykR2-POls">source code</a>):</p><pre>ch := make(chan int)<br>close(ch)<br>for range ch {<br>    fmt.Println(&quot;tick&quot;)<br>}<br>fmt.Println(&quot;done!&quot;)</pre><p>It printsdone! to stdout.</p><p>Range clause with channel supports only one (optional) iteration variable (<a href="https://play.golang.org/p/nf1NKaAOtwp">source code</a>):</p><pre>ch := make(chan int, 2)<br>ch &lt;- 1<br>ch &lt;- 2<br>close(ch)<br>for a, b := range ch {<br>}</pre><p>This program gives compile-time error: ./prog.go:8:14: too many variables in range.</p><p>If channel is not closed (<a href="https://play.golang.org/p/jkeSSsF7Mdd">source code</a>):</p><pre>ch := make(chan int)<br>for range ch {<br>}</pre><p>or <em>nil</em> channel is used (zero value for channel types) (<a href="https://play.golang.org/p/L5dSHmFyYoF">source code</a>):</p><pre>var ch chan int<br>for range ch {<br>}</pre><p>then <em>for </em>statement<em> </em>hangs forever and ultimately produces runtime error:</p><pre>fatal error: all goroutines are asleep - deadlock!</pre><h4>short variable declaration</h4><p>Variable defined in outer scope will be still reachable after <em>for</em> statement and its value will be set to value from last iteration (<a href="https://play.golang.org/p/latKTJiHGxd">source code</a>):</p><pre>nums := []string{&quot;zero&quot;, &quot;one&quot;, &quot;two&quot;}<br>var idx int<br>for idx = range nums {<br>}<br>fmt.Println(idx)</pre><p>Output is 2.</p><p>If variable within <em>range</em> clause will be declared using short variable declaration then its scope will be <em>for</em> statement (<a href="https://play.golang.org/p/fPaM12dcx0u">source code</a>):</p><pre>nums := []string{&quot;zero&quot;, &quot;one&quot;, &quot;two&quot;}<br>for idx := range nums {<br>}<br>fmt.Println(idx)</pre><p>This produce compile-time error undefined: idx.</p><h4>range clause and the address of iteration variable</h4><p>This topic has been described in one of previous stories so let’s link it here. It’s recommended to read it since it’s a trap many engineers fall into.</p><p><a href="https://medium.com/golangspec/range-clause-and-the-address-of-iteration-variable-b1796885d2b7">range clause and the address of iteration variable</a></p><h4>Resources</h4><ul><li><a href="https://golang.org/ref/spec#For_statements">The Go Programming Language Specification</a></li><li><a href="https://medium.com/golangspec/blocking-goroutine-forever-c443e7226632">Blocking goroutine forever</a></li><li><a href="https://medium.com/golangspec/range-over-channels-in-go-3d45dd825d2a">Range over channels in Go</a></li></ul><p>👏👏👏 below to help others discover this story. Please follow me here or on <a href="https://twitter.com/mlowicki">Twitter</a> if you want to get updates about new posts or boost work on future stories.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abcbdc011f81" width="1" height="1" alt=""><hr><p><a href="https://medium.com/golangspec/for-statement-and-its-all-faces-in-golang-abcbdc011f81">“for” statement and its all faces in Golang</a> was originally published in <a href="https://medium.com/golangspec">golangspec</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[range clause and the address of iteration variable]]></title>
            <link>https://medium.com/golangspec/range-clause-and-the-address-of-iteration-variable-b1796885d2b7?source=rss-5b90d60d16b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1796885d2b7</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Michał Łowicki]]></dc:creator>
            <pubDate>Fri, 06 Jul 2018 09:26:52 GMT</pubDate>
            <atom:updated>2018-07-06T09:26:52.441Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p>(<a href="https://play.golang.org/p/H1mtse3F1d_0">source code</a>)</p><pre>package main</pre><pre>import (<br>    &quot;fmt&quot;<br>)</pre><pre>type T struct {<br>    id int<br>}</pre><pre>func main() {<br>    t1 := T{id: 1}<br>    t2 := T{id: 2}<br>    ts1 := []T{t1, t2}<br>    ts2 := []*T{}<br>    for _, t := range ts1 {<br>        ts2 = append(ts2, &amp;t)<br>    }<br>    for _, t := range ts2 {<br>        fmt.Println((*t).id)<br>    }<br>}</pre><p>Think for a moment about expected output of this program..</p><p>For some (including me) the result might be surprising at first glance:</p><pre>2<br>2</pre><p>I’ve personally expected</p><pre>1<br>2</pre><p>but it turned out to be wrong answer.</p><p>Iteration variable <em>t</em> is declared using short variable declaration. Its scope is the block of the “for” statement. It’s a variable which during first iteration hold value of the first element and during 2nd iteration value of the second element . But it’s just another place in memory which hold current element of slice being iterated over. It doesn’t point to values stored inside slice’s underlying array — it’s a temporary bucket where next elements are copied over. So &amp;t will have the same value in each iteration since it’s a auxiliary variable to hold currently iterated element.</p><p>(<a href="https://play.golang.org/p/8ADFshqP4th">source code</a>)</p><pre>t1 := T{id: 1}<br>t2 := T{id: 2}<br>ts1 := []T{t1, t2}<br>ts2 := []*T{}<br>for _, t := range ts1 {<br>    <strong>t.id = 3</strong><br>    ts2 = append(ts2, &amp;t)<br>}<br>for _, t := range ts2 {<br>    fmt.Println((*t).id)<br>}<br>fmt.Println(ts1)<br>fmt.Println(t1)<br>fmt.Println(t2)</pre><p>output:</p><pre>3<br>3<br>[{1} {2}]<br>{1}<br>{2}</pre><p>Possible solution is to use index and get the address of slice’s element (<a href="https://play.golang.org/p/h2INlf-oDEX">source code</a>):</p><pre>t1 := T{id: 1}<br>t2 := T{id: 2}<br>ts1 := []T{t1, t2}<br>ts2 := []*T{}<br>for i, _ := range ts1 {<br>    ts2 = append(ts2, &amp;ts1[i])<br>}<br>for _, t := range ts2 {<br>    fmt.Println((*t).id)<br>}</pre><p>output:</p><pre>1<br>2</pre><h4>Resources</h4><p><a href="https://golang.org/ref/spec#For_range">https://golang.org/ref/spec#For_range</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1796885d2b7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/golangspec/range-clause-and-the-address-of-iteration-variable-b1796885d2b7">range clause and the address of iteration variable</a> was originally published in <a href="https://medium.com/golangspec">golangspec</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[sync.RWMutex]]></title>
            <link>https://medium.com/golangspec/sync-rwmutex-ca6c6c3208a0?source=rss-5b90d60d16b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca6c6c3208a0</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Michał Łowicki]]></dc:creator>
            <pubDate>Mon, 26 Mar 2018 14:28:26 GMT</pubDate>
            <atom:updated>2019-04-09T20:47:00.099Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmHZVxZmPP9w5iMqN7GWMw.jpeg" /></figure><h4>Solving readers-writers problems</h4><p>Readers-writers problems (plural since there’re some variations) occur when shared piece of data needs to be accessed by multiple threads. There’re two types of threads accessing data — readers and writers. Readers only read data and writers modify it. When writer has access to data then none other thread (reader or writer) can share such access. This constraint takes place in real life when e.g writer cannot modify data (like database) in atomic way so reading incomplete changes must be blocked to prevent loading corrupted data. There’re many modifications of the core problem like:</p><ul><li>writers cannot be starved (waiting indefinitely for their turn)</li><li>readers cannot be starved</li><li>no thread shall be allowed to starve</li></ul><p>Concrete implementation of multi-reader / single-writer mutual exclusion lock (like <a href="https://golang.org/pkg/sync/#RWMutex">sync.RWMutex</a>) solve one of readers-writers problems. Let’s see how it’s done in Go and what kind of guarantees it gives…</p><p>As a bonus we’ll look into profiling contended mutexes.</p><p>Article has been translated into Chinese —<a href="https://github.com/gocn/translator/blob/master/2019/w13_sync_mutex_translation.md"> here</a>.</p><h3>Usage</h3><p>Before diving into implementation details let’s see <em>sync.RWMutex</em> in action. Program below uses reader/writer mutex to protect critical section — sleep(). To visualise the whole process critical section is decorated with counting how many readers and writers are currently executing it (<a href="https://play.golang.org/p/xoiqW0RQQE9">source code</a>):</p><pre>package main</pre><pre>import (<br>    &quot;fmt&quot;<br>    &quot;math/rand&quot;<br>    &quot;strings&quot;<br>    &quot;sync&quot;<br>    &quot;time&quot;<br>)</pre><pre>func init() {<br>    rand.Seed(time.Now().Unix())<br>}</pre><pre>func sleep() {<br>    time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)<br>}</pre><pre>func reader(c chan int, m *sync.RWMutex, wg *sync.WaitGroup) {<br>    sleep()<br>    m.RLock()<br>    c &lt;- 1<br>    sleep()<br>    c &lt;- -1<br>    m.RUnlock()<br>    wg.Done()<br>}</pre><pre>func writer(c chan int, m *sync.RWMutex, wg *sync.WaitGroup) {<br>    sleep()<br>    m.Lock()<br>    c &lt;- 1<br>    sleep()<br>    c &lt;- -1<br>    m.Unlock()<br>    wg.Done()<br>}</pre><pre>func main() {<br>    var m sync.RWMutex<br>    var rs, ws int<br>    rsCh := make(chan int)<br>    wsCh := make(chan int)<br>    go func() {<br>        for {<br>            select {<br>            case n := &lt;-rsCh:<br>                rs += n<br>            case n := &lt;-wsCh:<br>                ws += n<br>            }<br>            fmt.Printf(&quot;%s%s\n&quot;, strings.Repeat(&quot;R&quot;, rs),<br>                    strings.Repeat(&quot;W&quot;, ws))<br>        }<br>    }()<br>    wg := sync.WaitGroup{}</pre><pre>    for i := 0; i &lt; 10; i++ {<br>        wg.Add(1)<br>        go reader(rsCh, &amp;m, &amp;wg)<br>    }<br>    for i := 0; i &lt; 3; i++ {<br>        wg.Add(1)<br>        go writer(wsCh, &amp;m, &amp;wg)<br>    }<br>    wg.Wait()<br>}</pre><blockquote>Environment of programs launched on play.golang.org is deterministic (e.g. when time begins) so rand.Seed(time.Now().Unix()) will provide the same seed value and the program’s output will be most likely the same. Either put different seed each time or run program on your machine.</blockquote><p>Sample output:</p><pre>W</pre><pre>R<br>RR<br>RRR<br>RRRR<br>RRRRR<br>RRRR<br>RRR<br>RRRR<br>RRR<br>RR<br>R</pre><pre>W</pre><pre>R<br>RR<br>RRR<br>RRRR<br>RRR<br>RR<br>R</pre><pre>W</pre><p>New line is printed each time set of goroutines (readers and writers) executing critical section changes. It’s visible that <em>RWMutex</em> allows for either at least one reader or exactly one writer.</p><p>What is also important and will be discussed further is that once writer calls Lock() then new readers are blocked. Writer waits for current set of readers to finish their jobs (departure) and when done writer is ready to go. It’s visible by decreasing number of readers one at a time and afterwards writer is displayed in a single line:</p><pre>...<br>RRRRR<br>RRRR<br>RRR<br>RR<br>R</pre><pre>W</pre><pre>...</pre><p>Once writer ends, previously blocked readers are resumed and next writer can start. Worth to know is the fact that if writer is done and there’re both readers and writers waiting then first readers will be unblocked and then writer. This way writer need to wait for the current set of readers so neither readers or writers will get starved.</p><h3>Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gg_vmyWlU35r3w_L4r4SYw.jpeg" /></figure><blockquote>Be warned that implementation being investigated (<a href="https://github.com/golang/go/blob/718d6c5880fe3507b1d224789b29bc2410fc9da5/src/sync/rwmutex.go">718d6c58</a>) can change any time.</blockquote><p><em>RWMutex</em> exposes two methods used by readers (<em>RLock</em> and <em>RUnlock</em>) and two dedicated for writers (<em>Lock</em> and <em>Unlock</em>).</p><h4>RLock</h4><p>For the sake of brevity let’s skip parts related to race detector (they will be replaced by ...).</p><pre>func (rw *RWMutex) RLock() {<br>    ...<br>    if atomic.AddInt32(&amp;rw.readerCount, 1) &lt; 0 {    <br>        runtime_SemacquireMutex(&amp;rw.readerSem, false)<br>    }<br>    ...<br>}</pre><p>Field <em>readerCount</em> is an <em>int32</em> value indicating number of pending readers — already reading data or blocked by writer. This is basically the number of readers which have called <em>RLock</em> function but no <em>RUnlock</em> yet.</p><p><a href="https://golang.org/pkg/sync/atomic/#AddInt32">atomic.AddInt32</a> is the atomic equivalent of:</p><pre>*addr += delta<br>return *addr</pre><p>where <em>addr</em> has type *int32 and <em>delta</em> has type int32. Because it’s atomic operation there is no risk that adding delta will interfere with other threads (more about <a href="https://en.wikipedia.org/wiki/Fetch-and-add">fetch-and-add</a>).</p><blockquote><em>If writers don’t come into play then </em>readerCount<em> is always greater than or equal to 0 and readers have fast non-blocking path involving only calls of </em>atomic.AddInt32.</blockquote><h4>Semaphore</h4><p>It’s a data structure invented by Edsger Dijkstra and it’s useful to solve many synchronization problems. It’s an integer with two operations:</p><ul><li><em>acquire</em> (known also as <em>wait</em>, <em>decrement</em> or P)</li><li><em>release</em> (<em>signal</em>, <em>increment</em> or <em>V</em>)</li></ul><p>Operation <em>acquire</em> decreases the semaphore by 1. If the result is negative then thread blocks and cannot resume until other thread will increment the semaphore. If result is positive then thread continues execution.</p><p>Operation <em>release</em> increases the semaphore by 1. If there’re blocked threads then one of them gets unblocked.</p><p>Go’s runtime provides <em>runtime_SemacquireMutex and runtime_Semrelease</em> functions which are used e.g. to implement <em>sync.RWMutex.</em></p><h4>Lock</h4><pre>func (rw *RWMutex) Lock() {<br>    ...<br>    rw.w.Lock()<br>    r := atomic.AddInt32(&amp;rw.readerCount, -rwmutexMaxReaders) + rwmutexMaxReaders<br>    if r != 0 &amp;&amp; atomic.AddInt32(&amp;rw.readerWait, r) != 0 {     <br>        runtime_SemacquireMutex(&amp;rw.writerSem, false)<br>    }<br>    ...<br>}</pre><p>Method <em>Lock</em> is used by writers to get exclusive access to shared data. First it’ll acquire a mutex <em>w</em> which excludes other writers. This mutex is unlocked at the very end of <em>Unlock</em> function. Next it decreases <em>readerCount</em> by <em>rwmutexMaxReaders</em> (1 &lt;&lt; 30). When <em>readerCount</em> becomes negative then <em>RLock</em> will block upcoming readers:</p><pre>if atomic.AddInt32(&amp;rw.readerCount, 1) &lt; 0 {<br>    // A writer is pending, wait for it.    <br>    runtime_SemacquireMutex(&amp;rw.readerSem, false)<br>}</pre><p>Since new readers will be blocked then what happens with readers already running? Field <em>readerWait is </em>used to remember current number of readers and block writer on semaphore. This semaphore will be unblocked when last reader unlocks the mutex in <em>RUnlock</em> method discussed below.</p><p>If there aren’t active readers then writer simply continues its execution.</p><h4>rwmutexMaxReaders</h4><p>In <a href="https://github.com/golang/go/blob/718d6c5880fe3507b1d224789b29bc2410fc9da5/src/sync/rwmutex.go">rwmutex.go</a> there is a constant:</p><pre>const rwmutexMaxReaders = 1 &lt;&lt; 30</pre><p>What it does and what is the meaning of 1 &lt;&lt; 30 number?</p><p>Field <em>readerCount</em> is of type <a href="https://golang.org/pkg/builtin/#int32">int32</a> so has range:</p><pre>[-1 &lt;&lt; 31, (1 &lt;&lt; 31) — 1] or [-2147483648, 2147483647]</pre><p><em>RWMutex</em> uses this field both for counting pending readers and to mark pending writer. In <em>Lock</em> method:</p><pre>r := atomic.AddInt32(&amp;rw.readerCount, -rwmutexMaxReaders) + rwmutexMaxReaders</pre><p>field <em>readerCount</em> is decreased by 1&lt;&lt;30. Negative value of <em>readerCount</em> means that writer is pending and readerCount + rwmutexMaxReaders is the current number of pending readers. It also limits how many readers can be pending. If we would have <em>rwmutexMaxReaders</em> or more pending readers then <em>readerCount</em> would be non-negative which would collapse the whole mechanism. So the actual limit on the number of readers is:</p><pre>rwmutexMaxReaders - 1</pre><p>which is still over a billion — 1073741823.</p><h4>RUnlock</h4><pre>func (rw *RWMutex) RUnlock() {<br>    ...<br>    if r := atomic.AddInt32(&amp;rw.readerCount, -1); r &lt; 0 {<br>        if r+1 == 0 || r+1 == -rwmutexMaxReaders {<br>            race.Enable()<br>            throw(&quot;sync: RUnlock of unlocked RWMutex&quot;)<br>        }<br>        // A writer is pending.<br>        if atomic.AddInt32(&amp;rw.readerWait, -1) == 0 {<br>            // The last reader unblocks the writer.       <br>            runtime_Semrelease(&amp;rw.writerSem, false)<br>        }<br>    }<br>    ...<br>}</pre><p>This method decrements <em>readerCount</em> (incremented by <em>RLock</em>). If <em>readerCount</em> is negative then it means that writer is either waiting or running. It’s because because <em>readerCount</em> has been decreased by <em>rwmutexMaxReaders</em> in <em>Lock</em> method. Afterwards it’s checked if number of departing readers (<em>readerWait</em>) is finally 0 because it means that writer can finally acquire semaphore.</p><h4>Unlock</h4><pre>func (rw *RWMutex) Unlock() {<br>    ...<br>    r := atomic.AddInt32(&amp;rw.readerCount, rwmutexMaxReaders)<br>    if r &gt;= rwmutexMaxReaders {<br>        race.Enable()<br>        throw(&quot;sync: Unlock of unlocked RWMutex&quot;)<br>    }<br>    for i := 0; i &lt; int(r); i++ {<br>        runtime_Semrelease(&amp;rw.readerSem, false)<br>    }<br>    rw.w.Unlock()<br>    ...<br>}</pre><p>To unlock the mutex held by writer first <em>readerCount</em> is increased by <em>rwmutexMaxReaders</em> so it’ll be again non-negative number. If <em>readerCount</em> is greater than zero then it means that some readers were waiting for writer to finish so now it’s time to wake them up. Afterwards writer mutex is released to allow writer to lock the <em>RWMutex</em> for writing.</p><p><em>Unlock</em> and <em>Runlock</em> methods will throw an error if reader or writer will try to unlock unlocked mutex (<a href="https://play.golang.org/p/YMdFET74olU">source code</a>):</p><pre>m := sync.RWMutex{}<br>m.Unlock()</pre><p>Output:</p><pre>fatal error: sync: Unlock of unlocked RWMutex<br>...</pre><h3>Recursive read locking</h3><p>Documentation says:</p><blockquote><em>If a goroutine holds a </em>RWMutex<em> for reading and another goroutine might call </em>Lock<em>, no goroutine should expect to be able to acquire a read lock until the initial read lock is released. In particular, this prohibits recursive read locking. This is to ensure that the lock eventually becomes available; a blocked </em>Lock<em> call excludes new readers from acquiring the lock.</em></blockquote><p><em>RWMutex</em> works in a way that if there is a pending writer then all attempts to call <em>RLock</em> will lock no matter if e.g. read lock has been already acquired (<a href="https://play.golang.org/p/XNndlaZ6Ema">source code</a>):</p><pre>package main</pre><pre>import (<br>    &quot;fmt&quot;<br>    &quot;sync&quot;<br>    &quot;time&quot;<br>)</pre><pre>var m sync.RWMutex</pre><pre>func f(n int) int {<br>    if n &lt; 1 {<br>        return 0<br>    }<br>    fmt.Println(&quot;RLock&quot;)<br>    m.RLock()<br>    defer func() {<br>        fmt.Println(&quot;RUnlock&quot;)<br>        m.RUnlock()<br>    }()<br>    time.Sleep(100 * time.Millisecond)<br>    return f(n-1) + n<br>}</pre><pre>func main() {<br>    done := make(chan int)<br>    go func() {<br>        time.Sleep(200 * time.Millisecond)<br>        fmt.Println(&quot;Lock&quot;)<br>        m.Lock()<br>        fmt.Println(&quot;Unlock&quot;)<br>        m.Unlock()<br>        done &lt;- 1<br>    }()<br>    f(4)<br>    &lt;-done<br>}</pre><p>Output:</p><pre>RLock<br>RLock<br>RLock<br>Lock<br>RLock<br>fatal error: all goroutines are asleep - deadlock!</pre><h3>Copying locks</h3><p>go tool vet is able to detect if locks are copied by value which can result in deadlocks. More about it in one of previous stories:</p><p><a href="https://medium.com/golangspec/detect-locks-passed-by-value-in-go-efb4ac9a3f2b">Detect locks passed by value in Go</a></p><h3>Performance</h3><p>Some time ago it was discovered that <em>RWMutex</em>’s performance degrades with increased number of CPU cores — <a href="https://github.com/golang/go/issues/17973">https://github.com/golang/go/issues/17973</a>.</p><h3>Contention</h3><p>Go ≥ 1.8 enables profiling contended mutex (<a href="https://github.com/golang/go/commit/ca922b6d363b6ca47822188dcbc5b92d912c7a4b">patch</a>). Let’s see how it works:</p><pre>package main</pre><pre>import (<br>    &quot;net/http&quot;<br>    _ &quot;net/http/pprof&quot;<br>    &quot;runtime&quot;<br>    &quot;sync&quot;<br>    &quot;time&quot;<br>)</pre><pre>func main() {<br>    var mu sync.Mutex<br>    runtime.SetMutexProfileFraction(5)<br>    for i := 0; i &lt; 10; i++ {<br>        go func() {<br>            for {<br>                mu.Lock()<br>                time.Sleep(100 * time.Millisecond)<br>                mu.Unlock()<br>            }<br>        }()<br>    }<br>    http.ListenAndServe(&quot;:8888&quot;, nil)<br>}</pre><pre>&gt; go build mutexcontention.go<br>&gt; ./mutexcontention</pre><p>While the program <em>mutexcontention</em> is running:</p><pre>&gt; go tool pprof mutexcontention <a href="http://localhost:8888/debug/pprof/mutex?debug=1">http://localhost:8888/debug/pprof/mutex?debug=1</a><br>Fetching profile over HTTP from <a href="http://localhost:8888/debug/pprof/mutex?debug=1">http://localhost:8888/debug/pprof/mutex?debug=1</a><br>Saved profile in /Users/mlowicki/pprof/pprof.mutexcontention.contentions.delay.003.pb.gz<br>File: mutexcontention<br>Type: delay<br>Entering interactive mode (type &quot;help&quot; for commands, &quot;o&quot; for options)<br>(pprof) list main<br>Total: 57.28s<br>ROUTINE ======================== main.main.func1 in /Users/mlowicki/projects/golang/src/github.com/mlowicki/mutexcontention/mutexcontention.go<br>0     57.28s (flat, cum)   100% of Total<br>.          .     14:   for i := 0; i &lt; 10; i++ {<br>.          .     15:           go func() {<br>.          .     16:                   for {<br>.          .     17:                           mu.Lock()<br>.          .     18:                           time.Sleep(100 * time.Millisecond)<br>.     57.28s     19:                           mu.Unlock()<br>.          .     20:                   }<br>.          .     21:           }()<br>.          .     22:   }<br>.          .     23:<br>.          .     24:   http.ListenAndServe(&quot;:8888&quot;, nil)</pre><p>What’s this 57.28s and why it points to mu.Unlock() ?</p><p>When goroutine blocks on mutex by calling <em>Lock</em> method then exact time when it happens is recorded — <em>acquiretime</em>. Afterwards when another goroutine unlocks that mutex and there is at least one goroutine waiting to acquire it then one of them is unblocked and <em>mutexevent</em> function is <a href="https://github.com/golang/go/blob/718d6c5880fe3507b1d224789b29bc2410fc9da5/src/runtime/sema.go#L186">called</a>. Function <em>mutexevent</em> checks if based on rate set by <a href="https://github.com/golang/go/blob/718d6c5880fe3507b1d224789b29bc2410fc9da5/src/runtime/mprof.go#L439">SetMutexProfileFraction</a> this particular event should be saved or discarded. Such event contains time spent on waiting (current time — acquiretime). In listing above total wait time across all goroutines blocked on particular mutex is gathered and displayed.</p><p>Contention on reader lock (<em>Rlock</em> and <em>RUnlock</em>) will be added in Go 1.11 (<a href="https://github.com/golang/go/commit/88ba64582703cea0d66a098730215554537572de">patch</a>).</p><h3>Resources</h3><ul><li>“The Little Book of Semaphores” by Allen B. Downey</li><li><a href="https://golang.org/pkg/sync/#RWMutex">Documentation of sync.RWMutex</a></li><li><a href="https://en.wikipedia.org/wiki/Readers–writers_problem">Readers-writers problem on Wikipedia</a></li><li><a href="https://medium.com/golangspec/reusable-barriers-in-golang-156db1f75d0b">Reusable barriers in Golang</a></li><li><a href="https://medium.com/golangspec/synchronization-queues-in-golang-554f8e3a31a4">Synchronization queues in Golang</a></li></ul><p>👏👏👏 below to help others discover this story. Please follow me here or on <a href="https://twitter.com/mlowicki">Twitter</a> if you want to get updates about new posts or boost work on future stories.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca6c6c3208a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/golangspec/sync-rwmutex-ca6c6c3208a0">sync.RWMutex</a> was originally published in <a href="https://medium.com/golangspec">golangspec</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Synchronization queues in Golang]]></title>
            <link>https://medium.com/golangspec/synchronization-queues-in-golang-554f8e3a31a4?source=rss-5b90d60d16b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/554f8e3a31a4</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Michał Łowicki]]></dc:creator>
            <pubDate>Mon, 12 Mar 2018 15:25:46 GMT</pubDate>
            <atom:updated>2018-03-12T15:25:46.075Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iDzVcACpJvVqFGj2WxYFIQ.jpeg" /></figure><h4>how to use channels to write idiomatic code in Go</h4><h3>Problem</h3><p>Let’s suppose we’re running an IT company employing programmers and testers. To give people a chance to get to know each other and relax a bit we’ve bought a ping-pong table and established following rules:</p><ul><li>exactly two people can play at the same time,</li><li>next pair can start their game only when previous one finished so it’s not allowed to switch one player,</li><li>testers can only work with programmers and vice versa (never two testers or two programmers together). If programmer or tester wants play then needs to wait for tester or programmer respectively to establish a valid pair.</li></ul><pre>func main() {<br>    for i := 0; i &lt; 10; i++ {<br>        go programmer()<br>    }<br>    for i := 0; i &lt; 5; i++ {<br>        go tester()<br>    }<br>    select {} // <a href="https://medium.com/golangspec/blocking-goroutine-forever-c443e7226632">long day at work...</a><br>}</pre><pre>func programmer() {<br>    for {<br>        code()<br>        pingPong()<br>    }<br>}</pre><pre>func tester() {<br>    for {<br>        test()<br>        pingPong()<br>    }<br>}</pre><p>We’ll mimic testing, coding and playing ping-pong by time.sleep:</p><pre>func test() {<br>    work()<br>}</pre><pre>func code() {<br>    work()<br>}</pre><pre>func work() {<br>    // Sleep up to 10 seconds.<br>    time.Sleep(time.Duration(rand.Intn(10000)) * time.Millisecond)<br>}</pre><pre>func pingPong() {<br>    // Sleep up to 2 seconds.<br>    time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond)<br>}</pre><pre>func programmer() {<br>    for {<br>        code()<br>        fmt.Println(&quot;Programmer starts&quot;)<br>        pingPong()<br>        fmt.Println(&quot;Programmer ends&quot;)</pre><pre>    }<br>}</pre><pre>func tester() {<br>    for {<br>        test()<br>        fmt.Println(&quot;Tester starts&quot;)<br>        pingPong()<br>        fmt.Println(&quot;Tester ends&quot;)<br>    }<br>}</pre><p>Such program emits stream of messages like this:</p><pre>&gt; go run pingpong.go<br>Tester starts<br>Programmer starts<br>Programmer starts<br>Tester ends<br>Programmer ends<br>Programmer starts<br>Programmer ends<br>Programmer ends</pre><p>But to play ping-pong in accordance with the rules our stream of messages can consists only of such 4-lines long sequences (in any order and repeated arbitrary number of times):</p><pre>Tester starts<br>Programmer starts<br>Tester ends<br>Programmer ends</pre><pre>Tester starts<br>Programmer starts<br>Programmer ends<br>Tester ends</pre><pre>Programmer starts<br>Tester starts<br>Tester ends<br>Programmer ends</pre><pre>Programmer starts<br>Tester starts<br>Programmer ends<br>Tester ends</pre><p>So first either tester or programmer approaches the table. Afterwards partner joins (programmer or tester accordingly). While leaving the game they can do it in any order. This is why we’ve 4 valid sequences.</p><p>Below are two solutions. 1st one is based on mutexes and 2nd one uses separate worker which coordinates the whole process making sure everything happens according to the policy.</p><h3>Solution #1</h3><p>Both solutions are using data structure which queues programmers and testers before approaching the table. When there is at least one valid pair available (Dev + QA) then one pair is allowed to play ping-pong.</p><pre>func tester(q *queue.Queue) {<br>    for {<br>        test()<br>        q.StartT()<br>        fmt.Println(&quot;Tester starts&quot;)<br>        pingPong()<br>        fmt.Println(&quot;Tester ends&quot;)<br>        q.EndT()<br>    }<br>}</pre><pre>func programmer(q *queue.Queue) {<br>    for {<br>        code()<br>        q.StartP()<br>        fmt.Println(&quot;Programmer starts&quot;)<br>        pingPong()<br>        fmt.Println(&quot;Programmer ends&quot;)<br>        q.EndP()<br>    }<br>}</pre><pre>func main() {<br>    q := queue.New()<br>    for i := 0; i &lt; 10; i++ {<br>        go programmer(q)<br>    }<br>    for i := 0; i &lt; 5; i++ {<br>        go tester(q)<br>    }<br>    select {}<br>}</pre><p>Package queue is defined as follows:</p><pre>package queue</pre><pre>import &quot;sync&quot;</pre><pre>type Queue struct {<br>    mut                   sync.Mutex<br>    numP, numT            int<br>    queueP, queueT, doneP chan int<br>}</pre><pre>func New() *Queue {<br>    q := Queue{<br>        queueP: make(chan int),<br>        queueT: make(chan int),<br>        doneP:  make(chan int),<br>    }<br>    return &amp;q<br>}</pre><pre>func (q *Queue) StartT() {<br>    q.mut.Lock()<br>    if q.numP &gt; 0 {<br>        q.numP -= 1<br>        q.queueP &lt;- 1<br>    } else {<br>        q.numT += 1<br>        q.mut.Unlock()<br>        &lt;-q.queueT<br>    }<br>}</pre><pre>func (q *Queue) EndT() {<br>    &lt;-q.doneP<br>    q.mut.Unlock()<br>}</pre><pre>func (q *Queue) StartP() {<br>    q.mut.Lock()<br>    if q.numT &gt; 0 {<br>        q.numT -= 1<br>        q.queueT &lt;- 1<br>    } else {<br>        q.numP += 1<br>        q.mut.Unlock()<br>        &lt;-q.queueP<br>    }<br>}</pre><pre>func (q *Queue) EndP() {<br>    q.doneP &lt;- 1<br>}</pre><p>Queue has mutex which serves two purposes:</p><ul><li>synchronizes access to shared counters (numT and numP)</li><li>acts as a token held by playing employees which blocks others from joing the table</li></ul><p>Programmers and testers are waiting for ping-pong parter using unbuffered channels:</p><pre>&lt;-q.queueP</pre><p>or</p><pre>&lt;-q.queueT</pre><p>Reading from one of these channels will block goroutine if there is no opponent available.</p><p>Let’s analyze StartT which is executed by testers:</p><pre>func (q *Queue) StartT() {<br>    q.mut.Lock()<br>    if q.numP &gt; 0 {<br>        q.numP -= 1<br>        q.queueP &lt;- 1<br>    } else {<br>        q.numT += 1<br>        q.mut.Unlock()<br>        &lt;-q.queueT<br>    }<br>}</pre><p>If numP is greater than 0 (there is at least one programmer waiting for the game) then number of waiting programmers is decreased by one and one of waiting programmer will be allowed to join the table (q.queueP &lt;- 1). What is interesting here is during this path mutex won’t be released so it’ll serve as a token giving exclusive access to ping-pong table.</p><p>If there is no waiting programmers then numT (number of waiting testers) is increased and goroutine blocks on &lt;-q.queueT.</p><p>StartP is basically the same but executed by programmers.</p><p>During the play, mutex will be locked so it needs to be released by either programmer or tester. To release mutex only when both parties finished the game a barrier doneP is used:</p><pre>func (q *Queue) EndT() {<br>    &lt;-q.doneP<br>    q.mut.Unlock()<br>}</pre><pre>func (q *Queue) EndP() {<br>    q.doneP &lt;- 1<br>}</pre><p>If programmer is still playing and tester finished then tester will block on &lt;-q.doneP. As soon as programmer reaches q.doneP &lt;- 1 then barrier will open and mutex will be released to allow these employees to go back to work.</p><p>If tester is still playing then programmer will block on q.doneP &lt;- 1. When tester is done then it reads from barrier &lt;-q.doneP which will unblock programmer and mutex will be released to free the table.</p><p>What is interesting here is that mutex is always released by tester even when either tester or programmer might locked it. It’s also part of reason why this solution might not be so obvious at first glance…</p><h3>Solution #2</h3><pre>package queue</pre><pre>const (<br>    msgPStart = iota<br>    msgTStart<br>    msgPEnd<br>    msgTEnd<br>)</pre><pre>type Queue struct {<br>    waitP, waitT   int<br>    playP, playT   bool<br>    queueP, queueT chan int<br>    msg            chan int<br>}</pre><pre>func New() *Queue {<br>    q := Queue{<br>        msg:    make(chan int),<br>        queueP: make(chan int),<br>        queueT: make(chan int),<br>    }<br>    go func() {<br>        for {<br>            select {<br>            case n := &lt;-q.msg:<br>                switch n {<br>                case msgPStart:<br>                    q.waitP++<br>                case msgPEnd:<br>                    q.playP = false<br>                case msgTStart:<br>                    q.waitT++<br>                case msgTEnd:<br>                    q.playT = false<br>                }<br>                if q.waitP &gt; 0 &amp;&amp; q.waitT &gt; 0 &amp;&amp; !q.playP &amp;&amp; !q.playT {<br>                    q.playP = true<br>                    q.playT = true<br>                    q.waitT--<br>                    q.waitP--<br>                    q.queueP &lt;- 1<br>                    q.queueT &lt;- 1<br>                }<br>            }<br>        }<br>    }()<br>    return &amp;q<br>}</pre><pre>func (q *Queue) StartT() {<br>    q.msg &lt;- msgTStart<br>    &lt;-q.queueT<br>}</pre><pre>func (q *Queue) EndT() {<br>    q.msg &lt;- msgTEnd<br>}</pre><pre>func (q *Queue) StartP() {<br>    q.msg &lt;- msgPStart<br>    &lt;-q.queueP<br>}</pre><pre>func (q *Queue) EndP() {<br>    q.msg &lt;- msgPEnd<br>}</pre><p>We’ve a central coordinator running inside separate goroutine which orchestrate the whole process. Scheduler gets information about new employee who wants to relax or if someone is done with ping-pong via msg channel. While receiving any message state of the scheduler is updated:</p><ul><li>number of waiting Devs or QAs is increased</li><li>information about playing employees is updated</li></ul><p>After receiving any of defined messages, scheduler will check if it’s allowed to start a game by another pair:</p><p>if q.waitP &gt; 0 &amp;&amp; q.waitT &gt; 0 &amp;&amp; !q.playP &amp;&amp; !q.playT {</p><p>If so the state is updated accordingly and one tester and one programmer are unblocked.</p><p>Instead of using mutexes (as in solution#1) to manage access to shared data, we’ve now a separate goroutine which talks with outside world over the channel. This gives us more idiomatic Go program.</p><blockquote><em>Don’t communicate by sharing memory, share memory by communicating.</em></blockquote><h3>Resources</h3><ul><li>“The Little Book of Semaphores” by Allen B. Downey</li><li><a href="https://medium.com/golangspec/reusable-barriers-in-golang-156db1f75d0b">https://medium.com/golangspec/reusable-barriers-in-golang-156db1 f75d0b</a></li><li><a href="https://blog.golang.org/share-memory-by-communicating">https://blog.golang.org/share-memory-by-communicating</a></li></ul><p>If you’ve found alternative solution you would like to share then please comment beneath.</p><p>👏👏👏 below to help others discover this story. Please follow me here or on <a href="https://twitter.com/mlowicki">Twitter</a> if you want to get updates about new posts or boost work on future stories.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=554f8e3a31a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/golangspec/synchronization-queues-in-golang-554f8e3a31a4">Synchronization queues in Golang</a> was originally published in <a href="https://medium.com/golangspec">golangspec</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reusable barriers in Golang]]></title>
            <link>https://medium.com/golangspec/reusable-barriers-in-golang-156db1f75d0b?source=rss-5b90d60d16b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/156db1f75d0b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[puzzle]]></category>
            <category><![CDATA[synchronization]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Michał Łowicki]]></dc:creator>
            <pubDate>Tue, 27 Feb 2018 18:21:19 GMT</pubDate>
            <atom:updated>2018-03-04T17:36:17.073Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hw-LbobDUM8SJeljTBL0Tg.jpeg" /></figure><h4>How to implement them using buffered channels</h4><p>In this story we’ll examine basic synchronization problem to see how concurrency primitives in Golang like buffered channels can be used to implement concise solutions.</p><h3>Problem</h3><p>Let’s suppose we’ve a number of workers. To take advantage of multiple CPU core every worker runs inside separate goroutine:</p><pre>for i := 0; i &lt; workers; i++ {<br>    go worker()<br>}</pre><p>Worker does a series of jobs:</p><pre>func worker() {<br>    for i := 0; i &lt; 3; i++ {<br>        job()<br>    }<br>}</pre><p>Each job is preceded with bootstrap that needs to be synchronized across all workers — worker needs to wait for all other workers to do their bootstrap before starting work on its own job:</p><pre>func worker() {<br>    for i := 0; i &lt; 3; i++ {<br>        bootstrap()<br>        <strong># wait for other workers to bootstrap</strong><br>        job()<br>    }<br>}</pre><p>There is one more thing. Bootstrap for loop <em>n</em> cannot be started if at least one worker still works on job from previous loop— bootstrap is used by following job so we cannot run another bootstrap if previous job is still being worked on:</p><pre>func worker() {<br>    for i := 0; i &lt; 3; i++ {<br>        <strong># wait for all workers to finish previous loop</strong><br>        bootstrap()<br>        <strong># wait for other workers to bootstrap</strong><br>        job()<br>    }<br>}</pre><p>Our bootstrap will be incrementing shared counter and our job will be sleep for some random time and then printing value of shared counter:</p><pre>type counter struct {<br>    c int<br>    sync.Mutex<br>}</pre><pre>func (c *counter) Incr() {<br>    c.Lock()<br>    c.c += 1<br>    c.Unlock()<br>}</pre><pre>func (c *counter) Get() (res int) {<br>    c.Lock()<br>    res = c.c<br>    c.Unlock()<br>    return<br>}</pre><pre>func worker(c *counter) {<br>    for i := 0; i &lt; 3; i++ {<br>        <strong># wait for all workers to finish previous loop</strong><br>        c.Incr()<br>        <strong># wait for other workers to do bootstrap</strong><br>        time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)<br>        fmt.Println(c.Get())<br>    }<br>}</pre><p>The goal is to write a program which prints numbers in the following way:</p><ul><li>only <em>n</em>, 2*<em>n</em> and 3*<em>n</em> numbers are allowed (since each worker executes 3 loops)</li><li>number is never less than number printed line above</li><li>each number should be displayed exactly <em>n</em> times</li></ul><p>Expected output with 3 workers:</p><pre>3<br>3<br>3<br>6<br>6<br>6<br>9<br>9<br>9</pre><p>Expected output with 2 workers:</p><pre>2<br>2<br>4<br>4<br>6<br>6</pre><p>Sample invalid output with 2 workers:</p><pre>2<br>4<br>2<br>4<br>6<br>6</pre><p>Think about possible solution(s). Next couple of lines are left blank intentionally to not show ready recipe right away.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>Workers will be synchronized by data structure called <strong>reusable barrier</strong>. Barrier consists of 2 gates. 1st gate is placed before incrementing the counter. It’s closed at the very beginning. Closed gate means that worker will be blocked when reaching it. Once every worker gets to gate 1. then:</p><ul><li>gate 2. (which is placed after increment) closes</li><li>gate 1. opens</li></ul><p>All workers increment shared counter and will successively reach gate 2 which is blocked. Once all workers get to 2nd gate then:</p><ul><li>gate 1. closes</li><li>gate 2. opens</li></ul><p>Workers can now work on jobs and then reach 1st gate again during next loop. The whole cycle starts again. Let’s visualize the whole process:</p><pre><br>     1st gate     2nd gate<br>        v             v<br>-w1--&gt;  |             |<br> --w2--&gt;|<br>--w3--&gt; |          <br> --w4--&gt;|             <br>-w5--&gt;  |             |</pre><pre> --w1--&gt;|             |<br> --w2--&gt;|             <br> --w3--&gt;|<br> --w4--&gt;|             <br> --w5--&gt;|             |</pre><pre>        |      --w1--&gt;|<br>               --w2--&gt;|<br>            --w3--&gt;   |<br>             --w4--&gt;  |<br>        |      --w5--&gt;|</pre><pre>        |      --w1--&gt;|<br>               --w2--&gt;|<br>               --w3--&gt;|<br>               --w4--&gt;|<br>        |      --w5--&gt;|</pre><pre>--w1--&gt; |             |<br>        |              --w2--&gt;<br> --w3--&gt;|<br>--w4--&gt; |             <br>        |             | --w5--&gt;</pre><p>Below are two solutions using above idea but their implementations are slightly different. Here is the code to test two proposed ideas:</p><pre>package main</pre><pre>import (<br>    &quot;fmt&quot;<br>    &quot;math/rand&quot;<br>    &quot;sync&quot;<br>    &quot;time&quot;</pre><pre>    // Set this import spec to point<br>    // to the copy of one of proposed<br>    // solutions.<br>    &quot;path/to/package/barrier&quot;<br>)</pre><pre>func init() {<br>    rand.Seed(time.Now().Unix())<br>}</pre><pre>type counter struct {<br>    c int<br>    sync.Mutex<br>}</pre><pre>func (c *counter) Incr() {<br>    c.Lock()<br>    c.c += 1<br>    c.Unlock()<br>}</pre><pre>func (c *counter) Get() (res int) {<br>    c.Lock()<br>    res = c.c<br>    c.Unlock()<br>    return<br>}</pre><pre>func worker(c *counter, br *barrier.Barrier, wg *sync.WaitGroup) {<br>    for i := 0; i &lt; 3; i++ {<br>        <strong>br.Before()</strong><br>        c.Incr()<br>        <strong>br.After()</strong><br>        time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)<br>        fmt.Println(c.Get())<br>    }<br>    wg.Done()<br>}</pre><pre>func main() {<br>    var wg sync.WaitGroup<br>    workers := 3<br>    br := barrier.New(workers)<br>    c := counter{}<br>    for i := 0; i &lt; workers; i++ {<br>        wg.Add(1)<br>        go worker(&amp;c, br, &amp;wg)<br>    }<br>    wg.Wait()<br>}</pre><p>Barrier must implement <em>Before</em> and <em>After</em> methods which are 1st and 2nd gates respectively.</p><h3>Solution #1</h3><p>Buffered channels with capacity 1 will be needed:</p><pre>ch := make(chan int, 1)</pre><p>Gate is implemented by receive from channel followed by sending to it:</p><pre>&lt;-ch<br>ch &lt;- 1</pre><p>If number of unread elements is 1 then gate is open. It’ll pass exactly one worker and then worker will enqueue new element to pass another worker which will put another element… (you see what is going on here).</p><p>If there’s no queued elements then gate is closed and worker will block on receiving from channel.</p><pre>// github.com/mlowicki/barrier<br>package barrier </pre><pre>import &quot;sync&quot;</pre><pre>type Barrier struct {<br>    c      int<br>    n      int<br>    m      sync.Mutex<br>    before chan int<br>    after  chan int<br>}</pre><pre>func New(n int) *Barrier {<br>    b := Barrier{<br>        n:      n,<br>        before: make(chan int, 1),<br>        after:  make(chan int, 1),<br>    }<br>    // close 1st gate<br>    b.after &lt;- 1  <br>    return &amp;b<br>}</pre><pre>func (b *Barrier) Before() {<br>    b.m.Lock()<br>    b.c += 1<br>    if b.c == b.n {<br>        // close 2nd gate<br>        &lt;-b.after<br>        // open 1st gate<br>        b.before &lt;- 1<br>    }<br>    b.m.Unlock()<br>    &lt;-b.before<br>    b.before &lt;- 1<br>}</pre><pre>func (b *Barrier) After() {<br>    b.m.Lock()<br>    b.c -= 1<br>    if b.c == 0 {<br>       // close 1st gate<br>       &lt;-b.before<br>       // open 2st gate<br>       b.after &lt;- 1<br>    }<br>    b.m.Unlock()<br>    &lt;-b.after<br>    b.after &lt;- 1<br>}</pre><h3>Solution #2</h3><p>This one uses buffered channels with capacity equal to the number of workers — <em>n</em>. Instead of going through each gate one worker by another, now we’ll put into channel exactly <em>n</em> elements just to pass all workers within single loop:</p><pre>// github.com/mlowicki/barrier2<br>package barrier</pre><pre>import &quot;sync&quot;</pre><pre>type Barrier struct {<br>    c      int<br>    n      int<br>    m      sync.Mutex<br>    before chan int<br>    after  chan int<br>}</pre><pre>func New(n int) *Barrier {<br>    b := Barrier{<br>        n:      n,<br>        before: make(chan int, n),<br>        after:  make(chan int, n),<br>    }<br>    return &amp;b<br>}</pre><pre>func (b *Barrier) Before() {<br>    b.m.Lock()<br>    b.c += 1<br>    if b.c == b.n {<br>        // open 2nd gate<br>        for i := 0; i &lt; b.n; i++ {<br>            b.before &lt;- 1<br>        }<br>    }<br>    b.m.Unlock()<br>    &lt;-b.before<br>}</pre><pre>func (b *Barrier) After() {<br>    b.m.Lock()<br>    b.c -= 1<br>    if b.c == 0 {<br>        // open 1st gate<br>        for i := 0; i &lt; b.n; i++ {<br>            b.after &lt;- 1<br>        }<br>    }<br>    b.m.Unlock()<br>    &lt;-b.after<br>}</pre><h3>Resources</h3><ul><li>“The Little Book of Semaphores” by Allen B. Downey</li></ul><p>If you’ve found alternative solution please share in comments.</p><p>👏👏👏 below to help others discover this story. Please follow me here or on <a href="https://twitter.com/mlowicki">Twitter</a> if you want to get updates about new posts or boost work on future stories.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=156db1f75d0b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/golangspec/reusable-barriers-in-golang-156db1f75d0b">Reusable barriers in Golang</a> was originally published in <a href="https://medium.com/golangspec">golangspec</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTPS proxies support in Go 1.10]]></title>
            <link>https://medium.com/@mlowicki/https-proxies-support-in-go-1-10-b956fb501d6b?source=rss-5b90d60d16b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b956fb501d6b</guid>
            <category><![CDATA[https]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[proxy]]></category>
            <dc:creator><![CDATA[Michał Łowicki]]></dc:creator>
            <pubDate>Wed, 21 Feb 2018 16:07:37 GMT</pubDate>
            <atom:updated>2018-02-21T16:17:44.107Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p>Couple of days ago Go 1.10 has been <a href="https://blog.golang.org/go1.10">released</a> — six months after 1.9. New version brings bigger and smaller changes (<a href="https://golang.org/doc/go1.10">release notes</a>) but I would like to discuss one related to net/http package. Version 1.10 supports proxies talking over HTTPS (<a href="https://github.com/hyangah/go/commit/ab0372d91c17ca97a8258670beadadc6601d0da2">commit</a>). Previously it was possible to communicate only with proxies using plain (unencrypted) HTTP. Let’s create an environment to confirm it actually works.</p><h4>Server</h4><p>To test this change please launch simple HTTP(S) proxy server written in Golang:</p><p><a href="https://medium.com/@mlowicki/http-s-proxy-in-golang-in-less-than-100-lines-of-code-6a51c2f2c38c">HTTP(S) Proxy in Golang in less than 100 lines of code</a></p><h4>Client</h4><pre>package main</pre><pre>import (<br>    &quot;crypto/tls&quot;<br>    &quot;fmt&quot;<br>    &quot;net/http&quot;<br>    &quot;net/http/httputil&quot;<br>    &quot;net/url&quot;<br>)</pre><pre>func main() {<br>    u, err := url.Parse(&quot;https://localhost:8888&quot;)<br>    if err != nil {<br>        panic(err)<br>    }<br>    tr := &amp;http.Transport{<br>        Proxy: http.ProxyURL(u),<br>        // Disable HTTP/2.<br>        TLSNextProto: make(map[string]func(authority string, c *tls.Conn) http.RoundTripper),<br>    }<br>    client := &amp;http.Client{Transport: tr}<br>    resp, err := client.Get(&quot;https://google.com&quot;)<br>    if err != nil {<br>        panic(err)<br>    }<br>    defer resp.Body.Close()<br>    dump, err := httputil.DumpResponse(resp, true)<br>    if err != nil {<br>        panic(err)<br>    }<br>    fmt.Printf(&quot;%q&quot;, dump)<br>}</pre><h4>1.9 vs 1.10</h4><pre>&gt; go version<br>go version go1.10 darwin/amd64<br>&gt; go run proxyclient.go<br>&quot;HTTP/1.1 200 OK\r\nTransfer-Encoding: ...</pre><pre>&gt; go version<br>go version go1.9 darwin/amd64<br>&gt; go run proxyclient.go<br>panic: Get https://google.com: malformed HTTP response &quot;\x15\x03\x01\x00\x02\x02\x16&quot;</pre><pre>...</pre><p>In the first output where Go 1.10 is used we’ve received correct response from <a href="https://google.com">https://google.com</a> proxied by server listening on <a href="https://localhost:8888">https://localhost:8888</a>. 2nd result shows that HTTP client in Go 1.9 is confused.</p><p>👏👏👏 below to help others discover this story. Please follow me here or on <a href="https://twitter.com/mlowicki">Twitter</a> if you want to get updates about new posts or boost work on future stories.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b956fb501d6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>