<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: dayvonjersen</title>
    <description>The latest articles on DEV Community by dayvonjersen (@dayvonjersen).</description>
    <link>https://dev.to/dayvonjersen</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F89596%2Fe6918862-3106-4fe9-9291-c32eb56042e2.png</url>
      <title>DEV Community: dayvonjersen</title>
      <link>https://dev.to/dayvonjersen</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/dayvonjersen"/>
    <language>en</language>
    <item>
      <title>How to use io.Reader and io.Writer</title>
      <dc:creator>dayvonjersen</dc:creator>
      <pubDate>Fri, 12 Apr 2019 07:21:04 +0000</pubDate>
      <link>https://dev.to/dayvonjersen/how-to-use-io-reader-and-io-writer-ao0</link>
      <guid>https://dev.to/dayvonjersen/how-to-use-io-reader-and-io-writer-ao0</guid>
      <description>&lt;p&gt;This was confusing for me when I started using Go after coming from other languages. &lt;/p&gt;

&lt;p&gt;Most of the technical articles and tutorials I came across made numerous references to &lt;a href="https://godoc.org/io#Reader"&gt;io.Reader&lt;/a&gt; and &lt;a href="https://godoc.org/io#Writer"&gt;io.Writer&lt;/a&gt;, interfaces provided by the &lt;a href="https://godoc.org/io"&gt;io package&lt;/a&gt;, describing them as excellent and easy-to-use but seemed to assume that the person reading already knew how to use them.&lt;/p&gt;

&lt;p&gt;Those abstractions are indeed powerful and convenient so here's how to actually use them in some common scenarios.&lt;/p&gt;

&lt;h2&gt;
  
  
  io.Reader
&lt;/h2&gt;

&lt;p&gt;Say you have some &lt;code&gt;reader&lt;/code&gt; which implements the io.Reader interface and you want to get the data out of it.&lt;/p&gt;

&lt;p&gt;You could make a slice of bytes &lt;strong&gt;with a capacity&lt;/strong&gt;, then pass the slice to &lt;code&gt;Read()&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight go"&gt;&lt;code&gt;&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;:=&lt;/span&gt; &lt;span class="nb"&gt;make&lt;/span&gt;&lt;span class="p"&gt;([]&lt;/span&gt;&lt;span class="kt"&gt;byte&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="m"&gt;512&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;reader&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Read&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Go slices are reference types which means when &lt;code&gt;Read()&lt;/code&gt; is called, &lt;code&gt;b&lt;/code&gt; will be &lt;em&gt;modified&lt;/em&gt; to contain the data from the &lt;code&gt;reader&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;However, &lt;code&gt;Read()&lt;/code&gt; will only copy as many bytes as the passed slice has capacity for.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Most of the time, gophers will reach for &lt;a href="https://godoc.org/io/ioutil#ReadAll"&gt;ioutil.ReadAll&lt;/a&gt; when they simply want all of the data at once.&lt;/p&gt;

&lt;p&gt;You could also use a &lt;a href="https://godoc.org/bytes#Buffer"&gt;byte buffer&lt;/a&gt; and &lt;a href="https://godoc.org/io#Copy"&gt;io.Copy&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;For example, here's a function I made and use all the time to get the contents of text files as a string (inspired or perhaps spoiled by php's &lt;a href="https://php.net/file-get-contents"&gt;file_get_contents()&lt;/a&gt;)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight go"&gt;&lt;code&gt;&lt;span class="k"&gt;func&lt;/span&gt; &lt;span class="n"&gt;fileGetContents&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;filename&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;contents&lt;/span&gt; &lt;span class="o"&gt;:=&lt;/span&gt; &lt;span class="nb"&gt;new&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;bytes&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Buffer&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;err&lt;/span&gt; &lt;span class="o"&gt;:=&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;filename&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;checkErr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;err&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;_&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;err&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;io&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Copy&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;contents&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;err&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;io&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;EOF&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;checkErr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;err&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="n"&gt;checkErr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Close&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;contents&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;checkErr()&lt;/code&gt; above is just &lt;code&gt;if err != nil { panic(err) }&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;But what if &lt;code&gt;reader&lt;/code&gt; is a stream of data with indeterminate (or neverending) length?&lt;/p&gt;

&lt;p&gt;In that case you want to reach for a &lt;a href="https://godoc.org/bufio#Scanner"&gt;bufio.Scanner&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight go"&gt;&lt;code&gt;&lt;span class="n"&gt;scanner&lt;/span&gt; &lt;span class="o"&gt;:=&lt;/span&gt; &lt;span class="n"&gt;bufio&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;NewScanner&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Stdin&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;scanner&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Scan&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;fmt&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;scanner&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Text&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  io.Writer
&lt;/h2&gt;

&lt;p&gt;To write data is very straightforward:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight go"&gt;&lt;code&gt;&lt;span class="n"&gt;someBytes&lt;/span&gt; &lt;span class="o"&gt;:=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;&lt;span class="kt"&gt;byte&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Hello world"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;err&lt;/span&gt; &lt;span class="o"&gt;:=&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"someFile.txt"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;checkErr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;err&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Write&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;someBytes&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Close&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Of course &lt;a href="https://godoc.org/io#WriteString"&gt;io.WriteString&lt;/a&gt; is less typing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight go"&gt;&lt;code&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;err&lt;/span&gt; &lt;span class="o"&gt;:=&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"someFile.txt"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;checkErr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;err&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;io&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;WriteString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Hello world"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;Close&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  A simple byte buffer
&lt;/h2&gt;

&lt;p&gt;There's nothing stopping you from implementing io.Reader and io.Writer in your own user-defined types.&lt;/p&gt;

&lt;p&gt;For example, here's a very useful, simple byte buffer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight go"&gt;&lt;code&gt;&lt;span class="k"&gt;type&lt;/span&gt; &lt;span class="n"&gt;buf&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;&lt;span class="kt"&gt;byte&lt;/span&gt;

&lt;span class="k"&gt;func&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;buf&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;Read&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;&lt;span class="kt"&gt;byte&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;err&lt;/span&gt; &lt;span class="kt"&gt;error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;copy&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)[&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="m"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;io&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;EOF&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;nil&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;func&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;buf&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;Write&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;&lt;span class="kt"&gt;byte&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;err&lt;/span&gt; &lt;span class="kt"&gt;error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="o"&gt;...&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="no"&gt;nil&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;func&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;buf&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;String&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I made it at first just to &lt;a href="https://github.com/generaltso/go-git-em-tiger/blob/e5ff73373269dd604a0cc6b5255f59c63d655636/cmd/tiger/cmd.go#L9-L41"&gt;capture the text output of shell commands in go&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  ʕ◔ϖ◔ʔ
&lt;/h2&gt;

&lt;p&gt;io.Reader and io.Writer are used all over the standard library from &lt;a href="https://godoc.org/os/exec#Cmd"&gt;shell commands&lt;/a&gt; to &lt;a href="https://godoc.org/net#Conn"&gt;networking&lt;/a&gt; even the &lt;a href="https://godoc.org/net/http#Response"&gt;http package&lt;/a&gt;!&lt;/p&gt;

&lt;p&gt;Hopefully now you know the basics of how to use readers and writers and maybe you can even try to implement io.Reader and io.Writer for your own user-defined types.&lt;/p&gt;

</description>
      <category>go</category>
      <category>beginners</category>
    </item>
    <item>
      <title>C++ For Go Programmers: Part 3 - Maps</title>
      <dc:creator>dayvonjersen</dc:creator>
      <pubDate>Thu, 06 Sep 2018 09:22:55 +0000</pubDate>
      <link>https://dev.to/dayvonjersen/c-for-go-programmers-part-3---maps-40dg</link>
      <guid>https://dev.to/dayvonjersen/c-for-go-programmers-part-3---maps-40dg</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;DISCLAIMER&lt;/strong&gt;: &lt;em&gt;This series title is inspired by &lt;a href="https://github.com/golang/go/wiki/GoForCPPProgrammers"&gt;a terrific article on the Go Wiki&lt;/a&gt;&lt;/em&gt; &lt;strong&gt;but, unlike that article&lt;/strong&gt;&lt;em&gt;, none of the information presented in this series should in any way be taken as sound advice. The author presumes on the part of the reader a competency in both modern C++ and Go which far exceeds the author's own. This is actually a thinly-veiled game devlog&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;code&gt;map&lt;/code&gt; is &lt;em&gt;easily&lt;/em&gt; the &lt;strong&gt;worst&lt;/strong&gt; built-in datatype in Go. I have an outline of the reasons why but we're not about negativity here. Besides, I'm pretty sure someone else has already written that article. &lt;/p&gt;

&lt;p&gt;Nope, we're not about that life. We're about exploring wonderful and exciting new possibilities in C++!!! ...by a combination of reinventing the wheel, baby duck syndrome, and eschewing well-defined best practices.&lt;/p&gt;

&lt;h2&gt;
  
  
  if ok {
&lt;/h2&gt;

&lt;p&gt;In Go, you can access a map value and check if it exists in one step:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;m := map[string]int{
    "one": 1,
    "two": 2,
}

one, ok := m["one"]     // 1, true
two, ok := m["two"]     // 2, true
three, ok := m["three"] // 0, false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;std::map&lt;/code&gt; in C++ does have &lt;code&gt;operator[]&lt;/code&gt; but its behavior is different:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Returns a reference to the value that is mapped to a key equivalent to key, &lt;strong&gt;performing an insertion if such key does not already exist.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;That's not what we want.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;std::map::find&lt;/code&gt; however, will allow us to determine if a value exists first.&lt;/p&gt;

&lt;p&gt;We don't have multiple return values in C++ so we'll have to pass a variable by reference to get the value.&lt;/p&gt;

&lt;p&gt;Here goes nothing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include &amp;lt;map&amp;gt;

template&amp;lt;typename K, typename V&amp;gt;
bool mapValue(std::map&amp;lt;K,V&amp;gt; m, K key, V&amp;amp; value) {
    auto it = m.find(key);
    if(it != m.end()) {
        value = it-&amp;gt;second;
        return true;
    }
    return false;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Adapting the Go example above somewhat, use it like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;std::map&amp;lt;std::string,int&amp;gt; m;
m["one"] = 1;
m["two"] = 2;

int one;
bool success = mapValue(m, std::string("one"), one);
if(success) {
    // ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;w00t&lt;/p&gt;




&lt;p&gt;This is actually the first time I've made a templated function and it was actually kinda fun even though I know I'm going down the path to ruin here (first you start sprinkling your code with some nice little generics every so often then you start doing metaprogramming next thing you know you're writing compile-time tetris and contributing to Boost)&lt;/p&gt;

&lt;p&gt;It should be noted that the implementation here won't work with &lt;em&gt;all&lt;/em&gt; types, notably C-style &lt;code&gt;char*&lt;/code&gt; strings (hence why I used &lt;code&gt;std::string&lt;/code&gt; in the example usage). &lt;/p&gt;

&lt;p&gt;And also I probably shouldn't be using &lt;code&gt;std::map&lt;/code&gt; at all for storing information for special tiles in my tilemaps but I'm not worried about it it's fine don't worry about it shhhhh&lt;/p&gt;

</description>
      <category>cpp</category>
      <category>go</category>
      <category>goodideas</category>
    </item>
    <item>
      <title>C++ For Go Programmers: Part 2 - Slices</title>
      <dc:creator>dayvonjersen</dc:creator>
      <pubDate>Wed, 15 Aug 2018 18:21:36 +0000</pubDate>
      <link>https://dev.to/dayvonjersen/c-for-go-programmers-part-2---slices-2771</link>
      <guid>https://dev.to/dayvonjersen/c-for-go-programmers-part-2---slices-2771</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;DISCLAIMER&lt;/strong&gt;: &lt;em&gt;This series title is inspired by &lt;a href="https://github.com/golang/go/wiki/GoForCPPProgrammers"&gt;a terrific article on the Go Wiki&lt;/a&gt;&lt;/em&gt; &lt;strong&gt;but, unlike that article&lt;/strong&gt;, &lt;em&gt;none of the information presented in this series should in any way be mistaken as good advice. &lt;a href="https://dev.toabout:blank#coming-soon-i-promise"&gt;See Part 0 for an introduction&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Seriously, don't do what I'm about to demo in this article. If you're using C++, just use &lt;a href="https://en.cppreference.com/w/cpp/container/vector"&gt;std::vector&lt;/a&gt;. If you're using C, check out &lt;a href="https://github.com/nothings/stb/blob/master/stretchy_buffer.h"&gt;stretchy buffers&lt;/a&gt;.&lt;br&gt;
&lt;strong&gt;EDIT&lt;/strong&gt;: Also I got slice semantics wrong. &lt;code&gt;s1 := s0[:]&lt;/code&gt; in Go actually makes &lt;a href="https://play.golang.org/p/AgiI3p902pI"&gt;both refer to the same underlying array&lt;/a&gt;, instead of making a copy. And &lt;code&gt;realloc()&lt;/code&gt; could screw things up too. Thanks to jstag on &lt;a href="//irc://irc.freenode.net/#go-nuts"&gt;#go-nuts&lt;/a&gt; for pointing these mistakes out.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As a thought experiment, let's try to implement Go slices in C and C++. If you don't want the play-by-play, take a look at &lt;a href="https://gist.github.com/dayvonjersen/2730d637c7e5950c43f655035f060183#file-slices-c"&gt;the finished product in C&lt;/a&gt; &lt;a href="https://gist.github.com/dayvonjersen/2730d637c7e5950c43f655035f060183#file-slices-cpp"&gt;and C++&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Part of what makes Go slices so nice is the convenient syntax:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;s0 := []int{1, 2, 3}       // literals
s1 := make([]byte, 0, 512) // or specify length and capacity
s2 := s0[1:]               // s2 == {2, 3}, s0 is still == {1, 2, 3}
s3 := s0[:] // create a copy of a slice
s3[2] = 5   // modify in-place
somethingThatImplementsioReader.Read(s1) // slices are reference types, s1 has data in it now (maybe)
s0 = append(s0, 4, 5, 6) // append implicitly resizes
s1 = append([]int{0}, append(s0[:1], s0[2:]...)...) // like I said, nice!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We'll have none of that happy nonsense. This is C.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;NOTE&lt;/strong&gt;: Go also has the very nice feature of being able to effortlessly convert its native utf8 &lt;code&gt;string&lt;/code&gt; type to and from either &lt;code&gt;[]byte&lt;/code&gt; or &lt;code&gt;[]rune&lt;/code&gt; types. I have no idea how to accomplish this in C/C++.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Slices in C
&lt;/h2&gt;

&lt;p&gt;A slice has a length, a capacity, and a pointer to an underlying array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;typedef struct _slice {
    int   len;
    int   cap;
    void* arr;
} slice;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The builtin functions &lt;a href="https://godoc.org/builtin#len"&gt;&lt;code&gt;len&lt;/code&gt;&lt;/a&gt; and &lt;a href="https://godoc.org/builtin#cap"&gt;&lt;code&gt;cap&lt;/code&gt;&lt;/a&gt; let you access the length and capacity of a slice.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int len(slice* s) { return s-&amp;gt;len; }
int cap(slice* s) { return s-&amp;gt;cap; }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So far this is pretty simple and straight-forward.&lt;/p&gt;

&lt;p&gt;But actually, we need to store the type information. Types are not first-class values in C, so we'll store the &lt;strong&gt;size of the type in bytes&lt;/strong&gt; and hope that's good enough. We'll come back to this later.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;typedef struct _slice {
    size_t type;
    int    len;
    int    cap;
    void*  arr;
} slice;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The builtin function &lt;a href="https://godoc.org/builtin#make"&gt;&lt;code&gt;make&lt;/code&gt;&lt;/a&gt; allocates a slice with a specified length and optionally a capacity.&lt;/p&gt;

&lt;p&gt;We'll require both and additionally the size (in bytes) of the type of the elements of the array as the first argument.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;slice* make(size_t type, int len, int cap) {
    slice* s = calloc(1, sizeof(slice));
    s-&amp;gt;arr   = calloc(cap, type);
    s-&amp;gt;type = type;
    s-&amp;gt;len  = len;
    s-&amp;gt;cap  = cap;
    return s;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Slicing a slice creates a new slice. We can't do bracket notation, however, so we'll make it a function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// naming stuff is hard
slice* sslice(slice* s, int start, int end) {
    int len = end-start;
    slice* s2 = make(s-&amp;gt;type, len, len);
    memcpy(s2-&amp;gt;arr, s-&amp;gt;arr + start * s-&amp;gt;type, len * s-&amp;gt;type);
    s2-&amp;gt;len = len;
    return s2;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here's where the fun begins with the pointer arithmetic. As you know, &lt;code&gt;arr[i]&lt;/code&gt; is just shorthand for &lt;code&gt;*(arr + i)&lt;/code&gt;, but the compiler needs to know the type of &lt;code&gt;arr&lt;/code&gt; in order for this to work. We're working with &lt;code&gt;void*&lt;/code&gt; here so we have to multiply the offsets by the size of the type in bytes.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;"The copy built-in function copies elements from a source slice into a destination slice. [...] The source and destination may overlap. Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst)."&lt;/p&gt;

&lt;p&gt;&lt;a href="https://godoc.org/builtin#copy"&gt;https://godoc.org/builtin#copy&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int copy(slice* dst, slice* src) {
    if(dst-&amp;gt;type != src-&amp;gt;type)  return 0; // should generate an error somehow actually
    int len = dst-&amp;gt;len &amp;lt; src-&amp;gt;len ? dst-&amp;gt;len : src-&amp;gt;len;
    memcpy(dst-&amp;gt;arr, src-&amp;gt;arr, len * src-&amp;gt;type);
    return len;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have enough now to start using these slices, but &lt;code&gt;append()&lt;/code&gt; is really what makes Go slices so valuable.&lt;/p&gt;

&lt;p&gt;If we knew the type of the underlying array we could do this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;typedef struct _int_slice {
    int  len;
    int  cap;
    int* arr;
} int_slice;

// same len, cap, make, sslice, and copy... except you could could omit type and use sizeof(int)

int_slice* append(slice* s, int elem) {
    if(s-&amp;gt;cap &amp;lt; s-&amp;gt;len+1) {
        s-&amp;gt;arr = realloc(s-&amp;gt;arr, sizeof(int) * s-&amp;gt;len+1);
        s-&amp;gt;cap = s-&amp;gt;len+1;
    }
    s-&amp;gt;arr[s-&amp;gt;len++] = elem;
    return s;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But since we want to have slices of &lt;em&gt;any&lt;/em&gt; type, we have to use &lt;code&gt;void*&lt;/code&gt;. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;NOTE&lt;/strong&gt;: As a consequence, we cannot pass literals or value types to our &lt;code&gt;append()&lt;/code&gt;, we always have to pass a pointer type. Something like &lt;code&gt;int a = 5; s = append(s, &amp;amp;a);&lt;/code&gt; worked in my little toy examples but it's not great. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Recall that in C a byte is an &lt;code&gt;unsigned char&lt;/code&gt;, and we have the size in bytes of the type of each individual element stored, thus:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;slice* append(slice* s, void* elem) {
    if(s-&amp;gt;cap &amp;lt; s-&amp;gt;len+1) {
        s-&amp;gt;arr = realloc(s-&amp;gt;arr, s-&amp;gt;type * s-&amp;gt;len+1);
        s-&amp;gt;cap = s-&amp;gt;len+1;
    }
    int offset = s-&amp;gt;len * s-&amp;gt;type;
    for(int i = 0; i &amp;lt; s-&amp;gt;type; i++) {
        *((unsigned char*)s-&amp;gt;arr + offset + i) = *((unsigned char*)elem + i);
    }
    s-&amp;gt;len += 1;
    return s;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;"Ah", I can almost hear you say now, "but the real &lt;code&gt;append()&lt;/code&gt; takes variadic arguments!" I got you covered, family:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;slice* append(int count, slice* s, ...) {
    va_list args;
    va_start(args, s);

    if(s-&amp;gt;cap &amp;lt; s-&amp;gt;len+count) {
        s-&amp;gt;arr = realloc(s-&amp;gt;arr, s-&amp;gt;type * s-&amp;gt;len+count);
        s-&amp;gt;cap = s-&amp;gt;len+count;
    }

    int offset = s-&amp;gt;len * s-&amp;gt;type;
    for(int j = 0; j &amp;lt; count; j++) {
        unsigned char* elem = va_arg(args, unsigned char*);
        for(int i = 0; i &amp;lt; s-&amp;gt;type; i++) {
            *((unsigned char*)s-&amp;gt;arr + offset + i + j*s-&amp;gt;type) = elem[i];
        }
    }
    va_end(args);

    s-&amp;gt;len += count;
    return s;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Unfortunately, we have to specify how many elements we're appending because &lt;code&gt;&amp;lt;stdarg.h&amp;gt;&lt;/code&gt; provides no mechanism for counting the number of variadic args. This is entirely consistent with how C expects the programmer to constantly keep track of the length of arrays and will happily read off the end and Segfault on your face, leading back around to why you would want to use something like slices in the first place.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;full source code: &lt;a href="https://gist.github.com/dayvonjersen/2730d637c7e5950c43f655035f060183#file-slices-c"&gt;slices.c&lt;/a&gt;&lt;/strong&gt; 👀&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Don't forget to &lt;code&gt;free()&lt;/code&gt; your slices and their underlying arrays when you're finished with them.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Slices in  C++
&lt;/h2&gt;

&lt;p&gt;So now we have Go slices in C, but C++ (and its creator) will scream at us if we try to compile this code. It's just a matter of casting the return value of *alloc and ignoring and/or turning off some compiler warnings, but let's try to do it the right way™ with classes and templates:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;template&amp;lt;typename T&amp;gt;
class slice {
    int _len;
    int _cap;
    T*  _arr;
public:
    slice(int len) : slice(len,len) {}
    slice(int len, int cap) {
        _len = len;
        _cap = cap;
        _arr = (T*) calloc(cap, sizeof(T));
    }
    ~slice() {
        free(_arr);
    }

    int len() { return _len; }
    int cap() { return _cap; }

    T&amp;amp; operator[](int i) { return _arr[i]; }

    void append(T elem) {
        if(_cap &amp;lt; _len+1) {
            _arr = (T*) realloc(_arr, _len+1 * sizeof(T));
            _cap = _len+1;
        }
        _arr[_len++] = elem;
    }

    template&amp;lt;typename... Targs&amp;gt;
    void append(T elem, Targs... args) {
        append(elem);
        append(args...);
    }

    slice&amp;lt;T&amp;gt; sslice(int start, int end) {
        int len = end-start;
        slice&amp;lt;T&amp;gt; s2(0, len);
        for(int i = 0; i &amp;lt; len; i++) {
            s2.append(_arr[start + i]);
        }
        return s2;
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;full source code: &lt;a href="https://gist.github.com/dayvonjersen/2730d637c7e5950c43f655035f060183#file-slices-cpp"&gt;slices.cpp&lt;/a&gt;&lt;/strong&gt; 👀&lt;/p&gt;

&lt;p&gt;Templates let us have slices of any type without having to do any pointer arithmetic or obscene casting.&lt;/p&gt;

&lt;p&gt;I think I'm starting to sound a little too much like Bjarne so I should skip the play-by-play and wrap this up quickly.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;NOTE&lt;/strong&gt;: I had to use stdlib *alloc and friends because &lt;code&gt;new[]&lt;/code&gt; for an &lt;em&gt;unbounded&lt;/em&gt; array class member led to some strange results...&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Bonuses for using C++:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;We get to have &lt;code&gt;free()&lt;/code&gt; called in the destructor automatically &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Bracket notation for accessing slice elements directly.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Constructor overloading lets us get the same arguments as Go's &lt;code&gt;make()&lt;/code&gt; (can omit capacity)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;C++11 introduced parameter pack for variadic arguments, very nicely explained here by &lt;a href="http://kevinushey.github.io/blog/2016/01/27/introduction-to-c++-variadic-templates/"&gt;this fine fellow&lt;/a&gt;. I'm not crazy about having to use recursion but realistically you'd never append enough elements in a single call to overflow the stack.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  The End
&lt;/h2&gt;

&lt;p&gt;In conclusion, don't do this. You get none of the convenient syntax of Go slices nor any of the flexibility of conversions between Go strings and &lt;code&gt;[]byte&lt;/code&gt; or &lt;code&gt;[]rune&lt;/code&gt; while having to manage your own memory. &lt;code&gt;realloc()&lt;/code&gt;'ing all the time can't be good for performance and you'll leak memory if you forget to &lt;code&gt;free()&lt;/code&gt; every slice, especially since slicing a slice creates a new slice every time. Again, if you're using C++ just use &lt;a href="https://en.cppreference.com/w/cpp/container/vector"&gt;std::vector&lt;/a&gt; otherwise check out &lt;a href="https://github.com/nothings/stb/blob/master/stretchy_buffer.h"&gt;stretchy buffers&lt;/a&gt;. Both of those check for OOM conditions and weren't hacked together in 30 minutes to write a follow-up article for a series that isn't even really a series.&lt;/p&gt;

</description>
      <category>c</category>
      <category>cpp</category>
      <category>go</category>
      <category>badideas</category>
    </item>
    <item>
      <title>C++ For Go Programmers: Part 1 - Struct Embedding, Object Receivers, and Interfaces in C++</title>
      <dc:creator>dayvonjersen</dc:creator>
      <pubDate>Sat, 11 Aug 2018 10:28:04 +0000</pubDate>
      <link>https://dev.to/dayvonjersen/c-for-go-programmers-part-1---struct-embedding-object-receivers-and-interfaces-in-c-27pf</link>
      <guid>https://dev.to/dayvonjersen/c-for-go-programmers-part-1---struct-embedding-object-receivers-and-interfaces-in-c-27pf</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;DISCLAIMER&lt;/strong&gt;: &lt;em&gt;This series title is inspired by &lt;a href="https://github.com/golang/go/wiki/GoForCPPProgrammers"&gt;a terrific article on the Go Wiki&lt;/a&gt; but, unlike that article, none of the information presented in this series should in any way be taken as sound advice. The author presumes a core competency in both modern C++  and Go on the part of the reader which exceeds the author's own. It is a thinly veiled call for help from a disturbed individual with too much time on his hands and an irrational fear of traditional OOP. See Part 0 for an introduction.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Struct Embedding
&lt;/h3&gt;

&lt;p&gt;Go provides struct embedding as &lt;del&gt;the only&lt;/del&gt; &lt;u&gt;an&lt;/u&gt; alternative to inheritance:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight mosel"&gt;&lt;code&gt;&lt;span class="k"&gt;package&lt;/span&gt; &lt;span class="n"&gt;main&lt;/span&gt;

&lt;span class="n"&gt;type&lt;/span&gt; &lt;span class="n"&gt;parent&lt;/span&gt; &lt;span class="n"&gt;struct&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="n"&gt;something&lt;/span&gt; &lt;span class="n"&gt;int&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="n"&gt;type&lt;/span&gt; &lt;span class="n"&gt;child&lt;/span&gt; &lt;span class="n"&gt;struct&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="n"&gt;parent&lt;/span&gt;
  &lt;span class="n"&gt;somethingElse&lt;/span&gt; &lt;span class="n"&gt;float64&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="n"&gt;func&lt;/span&gt; &lt;span class="n"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="p"&gt;:=&lt;/span&gt; &lt;span class="n"&gt;child&lt;/span&gt;&lt;span class="p"&gt;{}&lt;/span&gt;
  &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;something&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="m"&gt;42&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;But if you &lt;code&gt;fmt.Printf("%#v", c)&lt;/code&gt; you'd see how this actually works:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;main.child{
  parent:main.parent{something:42},
  somethingElse:0
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;And indeed you can access &lt;code&gt;something&lt;/code&gt; by doing &lt;code&gt;c.parent.something&lt;/code&gt; as well.&lt;/p&gt;

&lt;p&gt;Therefore, on a conceptual level at least, the C++ equivalent is:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct parent {
  int something;
};

struct child {
  parent parent;
  double somethingElse;
};

int main() {
  child c = {0};
  c.parent.something = 42;

  return 0;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The same holds true for C, barring some &lt;code&gt;typedef&lt;/code&gt;'s and this is nothing new. C programmers do this sort of thing all the time.&lt;/p&gt;

&lt;p&gt;Ergo, we can have inherited members by using struct fields.&lt;/p&gt;

&lt;h3&gt;
  
  
  Object Receivers
&lt;/h3&gt;

&lt;p&gt;Go allows us to define methods on our defined types. Not only with structs, but let's keep things simple.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type myStruct struct {
  something int
}

func (s *myStruct) Method() {
  s.something = 42
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The object receiver is of a pointer type, rather than as a value in order to effect changes when called&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;s1 := &amp;amp;myStruct{}
s1.Method() // s1.something == 42
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Conceptually, this is equivalent to:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func Method(s* myStruct) {
  s.something = 42
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;And indeed the C/C++ equivalent is something very commonly found in C code:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct my_struct {
  int something;
};

my_struct_method(my_struct* s) {
  s-&amp;gt;something = 42;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Object receivers as the first argument to a function which acts on a struct is the defacto way of declaring "methods" on an "object" in C and is valid C++. This is nothing new.&lt;/p&gt;

&lt;h3&gt;
  
  
  Interfaces
&lt;/h3&gt;

&lt;p&gt;Let's combine what we've established so far and do something completely bananas.&lt;/p&gt;

&lt;p&gt;Go's interface model, to paraphrase Commander Pike, is&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If an object has all the methods of an interface, then it satisfies that interface.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Have some code:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#include &amp;lt;stdlib.h&amp;gt;

#include &amp;lt;functional&amp;gt;
#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;

struct some_interface {
  std::function&amp;lt;void()&amp;gt;* Method;
};

some_interface* new_some_interface() {
  return (some_interface*) calloc(1, sizeof(some_interface));
}

struct parent {
  some_interface* some_interface;
};

parent* new_parent() {
  parent* p = (parent*) calloc(1, sizeof(parent));
  p-&amp;gt;some_interface = nullptr;
  return p;
}

struct child {
  parent* parent;
  int something;
};

child* new_child() {
  return (child*) calloc(1, sizeof(child));
}

child_method(child* c) {
  c-&amp;gt;something = 42;
}

int main() {
  child* c1  = new_child();
  child* c2  = new_child();
  c1-&amp;gt;parent = new_parent();
  c2-&amp;gt;parent = new_parent();

  c1-&amp;gt;parent-&amp;gt;some_interface = new_some_interface();
  c1-&amp;gt;parent-&amp;gt;some_interface-&amp;gt;Method = new std::function&amp;lt;void()&amp;gt;([=]() -&amp;gt; void {
    child_method(c1);
  });

  std::vector&amp;lt;parent*&amp;gt; parents;
  parents.push_back(c1-&amp;gt;parent);
  parents.push_back(c2-&amp;gt;parent);

  for(auto p : parents) {
    if(p-&amp;gt;some_interface != nullptr) {
      (*p-&amp;gt;some_interface-&amp;gt;Method)();
    }
  }

  std::cout &amp;lt;&amp;lt; "c1.something: " &amp;lt;&amp;lt; c1-&amp;gt;something &amp;lt;&amp;lt; "\n";
  std::cout &amp;lt;&amp;lt; "c2.something: " &amp;lt;&amp;lt; c2-&amp;gt;something &amp;lt;&amp;lt; "\n";

  return 0;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now if you're still with me and you haven't closed the browser tab in utter disgust let me explain all this and why I think it's easier to think about than polymorphism and inheritance (even if it's much harder to look at).&lt;/p&gt;

&lt;h4&gt;
  
  
  How it works
&lt;/h4&gt;

&lt;p&gt;The &lt;code&gt;parent&lt;/code&gt; is an ancestor, equivalent to an abstract base class in some ways. It holds pointers to all the interfaces that "subclasses" might have, but unlike abstract virtual functions, all of those methods do not necessarily have to be defined by subclasses. When calling methods on a parent, one simply checks if the interface has been defined first before calling the desired method.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;parent&lt;/code&gt;'s are "inherited" by subclasses such as &lt;code&gt;child&lt;/code&gt;, but one could imagine &lt;code&gt;step_child&lt;/code&gt; and &lt;code&gt;adopted_orphan&lt;/code&gt; having a &lt;code&gt;parent&lt;/code&gt; field as well. &lt;code&gt;parent&lt;/code&gt;'s are what are passed around because they expose the interface their &lt;code&gt;children&lt;/code&gt; define.&lt;/p&gt;

&lt;p&gt;Those definitions come in the form of C++ &lt;code&gt;lambda&lt;/code&gt; functions &lt;sup&gt;new in c++11!&lt;/sup&gt; because they are closures which can capture variables in the surrounding scope.&lt;/p&gt;

&lt;p&gt;But they can just as easily be regular C function pointers just that that requires casting back and forth from void* to an explicit type:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// sorry that this example is so different from the one above but it's what i had on hand

#include &amp;lt;stdio.h&amp;gt;

typedef struct _interface {
    int(*CommonMethod)(void*);
} _interface;

typedef struct object_a {
    int prop;
    _interface iface;
} object_a;

typedef struct object_b {
    int different_prop;
    _interface iface;
} object_b;

void func_that_takes_interface(void* obj, _interface iface) {
    printf("%d\n", iface.CommonMethod(obj));
}

int object_a_common_method(void* obj) {
    object_a* a = (object_a*)obj;
    return a-&amp;gt;prop * a-&amp;gt;prop;
}

int object_b_common_method(void* obj) {
    object_b* b = (object_b*)obj;
    return b-&amp;gt;different_prop * 2;
}

int main() {
    object_a a = {0};
    object_b b = {0};

    a.iface.CommonMethod = object_a_common_method;
    b.iface.CommonMethod = object_b_common_method;

    func_that_takes_interface((void*)&amp;amp;a, a.iface);
    func_that_takes_interface((void*)&amp;amp;b, b.iface);

    a.prop = 9;
    b.different_prop = 9;

    func_that_takes_interface((void*)&amp;amp;a, a.iface);
    func_that_takes_interface((void*)&amp;amp;b, b.iface);

    a.prop = 4;
    b.different_prop = 10;

    func_that_takes_interface((void*)&amp;amp;a, a.iface);
    func_that_takes_interface((void*)&amp;amp;b, b.iface);

    return 0;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;It should be noted that C++ &lt;code&gt;lambda&lt;/code&gt;'s not only let you forgo this inconvenience but let you define a function body inline (which is what they were actually designed for...) but that goes against what I'm about to say next:&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In either case, we can provide a regular function that takes an &lt;code&gt;object receiver&lt;/code&gt; to serve as the function which satisfies a interface method. In this way, interfaces are not required to interface with a particular method that acts on a set of data but can be used when such situations arise that the sets of data, though with similar methods defined are of differing types.&lt;/p&gt;

&lt;h4&gt;
  
  
  Implementation details
&lt;/h4&gt;

&lt;p&gt;&lt;code&gt;std::function&amp;lt;&amp;gt;&lt;/code&gt; is necessary to hold pointers to &lt;code&gt;lambda&lt;/code&gt;'s. The one defined above is actually of type &lt;code&gt;main::lambda&amp;lt;void()&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Heap allocations are necessary even in this toy example.&lt;/p&gt;

&lt;p&gt;The corresponding &lt;code&gt;free&lt;/code&gt; functions are omitted for clarity above but are necessary nonetheless:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;free_parent(parent* p) {
  if(p-&amp;gt;some_interface != nullptr) {
    delete p-&amp;gt;some_interface-&amp;gt;Method;
  }
  free(p);
}

free_child(child* c) {
  free_parent(c-&amp;gt;parent);
  free(c);
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;h4&gt;
  
  
  In Practise
&lt;/h4&gt;

&lt;p&gt;I'm making a game. Every &lt;code&gt;player&lt;/code&gt;, &lt;code&gt;enemy&lt;/code&gt;, and &lt;code&gt;npc&lt;/code&gt; has an &lt;code&gt;entity&lt;/code&gt; struct field. That entity has interfaces such as &lt;code&gt;renderable&lt;/code&gt; and &lt;code&gt;updateable&lt;/code&gt; which are called by the game loop. It's working as intended so far. I need to add &lt;code&gt;collidable&lt;/code&gt; and &lt;code&gt;interactable&lt;/code&gt; next but I'm too busy being a &lt;code&gt;nodev&lt;/code&gt;&lt;/p&gt;

</description>
      <category>cpp</category>
      <category>go</category>
      <category>badadvice</category>
      <category>herebedragons</category>
    </item>
  </channel>
</rss>
