<?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 Michael Ernst on Medium]]></title>
        <description><![CDATA[Stories by Michael Ernst on Medium]]></description>
        <link>https://medium.com/@mier85?source=rss-2f154a981138------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HDGeqRAbfqwtVloE.</url>
            <title>Stories by Michael Ernst on Medium</title>
            <link>https://medium.com/@mier85?source=rss-2f154a981138------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 16:40:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mier85/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[golang 1.18+ generics: The Good, The Bad, The Ugly.]]></title>
            <link>https://itnext.io/golang-1-18-generics-the-good-the-bad-the-ugly-5e9fa2520e76?source=rss-2f154a981138------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e9fa2520e76</guid>
            <category><![CDATA[antipattern]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Michael Ernst]]></dc:creator>
            <pubDate>Wed, 22 Dec 2021 23:14:51 GMT</pubDate>
            <atom:updated>2022-01-18T19:56:28.320Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aAES3oN8i6dJiA5vzqVioA.png" /></figure><h3>Introduction</h3><p>Generics are awesome and golang is getting even more handy than it was before. But similar to channels, which can be very useful, we shouldn’t use them everywhere just because they exist ( see <a href="https://opensource.com/article/17/9/seven-stages-becoming-go-programmer">Stage 4</a> ).</p><p>There are <strong>good</strong> use-cases, even if not simply used in data-structures. There are <strong>bad</strong> use-cases, like a generic logger. And there are solutions that could be used, but are rather ugly.</p><p>And then there is something that is REALLY ugly.</p><p>Let’s look at an example for each!</p><h3>The Good</h3><p>What I really dreamed of doing in golang and what I think I can finally do now, is a generic provider for a CRUD endpoint:</p><pre>type Model interface{<br>    ID() string<br>}</pre><pre>type DataProvider[MODEL Model] interface {<br>    FindByID(id string) (MODEL, error)<br>    List() ([]MODEL, error)<br>    Update(id string, model MODEL) error<br>    Insert(model MODEL) error<br>    Delete(id string) error<br>}</pre><p>This is a big interface and you could shorten it depending on what you need in your exact use-case, but however, for the sake of some completeness, there it is.</p><p>Now you can define a HTTP handler that is using the DataProvider:</p><pre>type HTTPHandler[MODEL Model] struct {<br>    dataProvider DataProvider[MODEL]<br>}</pre><pre>func (h HTTPHandler[MODEL]) FindByID(rw http.ResponseWriter, req *http.Request) {<br>    // validate request here   </pre><pre>    id = // extract id here</pre><pre>model, err := h.dataProvider.FindByID(id)<br>    if err != nil { <br>        // error handling here<br>        return<br>    }<br>    err = json.NewEncoder(rw).Encode(model)<br>    if err != nil { <br>        // error handling here<br>        return<br>    }<br>}</pre><p>As you can see, we can implement this once for each method, and then we are done. We could even create a client on the opposite side of things, which we only need to implement once for basic methods.</p><p>Why are we using generics here and not simply the Model interface that we already define anyway?</p><p>Well, there are a few advantages of generics over using the Model type itself here:</p><ol><li>With the generic approach, the DataProvider does not at all need to be aware of the Model and it does not need to implement it. It can simply provide it’s concrete types which is very powerful ( but could still be abstracted for simple use cases )</li><li>We can extend this solution and do operations with concrete types. Let’s see how a validator for an Insert or Update could look like.</li></ol><pre>type HTTPHandler[MODEL any] struct {<br>    dataProvider DataProvider[MODEL]<br>    InsertValidator func(new MODEL) error<br>    UpdateValidator func(old MODEL, new MODEL) error</pre><pre>}</pre><p>In this validator lies the true strength of the generic approach here. We will unmarshal the HTTP request, and if there is a custom InsertValidator defined, then we can use it to validate whether the model checks out, and we can do it in a type safe way and work with the concrete model:</p><pre>type User struct {<br>    FirstName string<br>    LastName string<br>}</pre><pre>func InsertValidator(u User) error {<br>    if u.FirstName == &quot;&quot; { ... } <br>    if u.LastName == &quot;&quot; { ... }<br>}</pre><p>So we have a generic handler, which we can tweak with custom callbacks, which directly get us the payload. No type-casts. No maps. Just the struct itself!</p><h3>The Bad</h3><p>Let’s pick up the generic logger I wrote about in <a href="https://medium.com/@mier85/self-referencing-interfaces-in-golang-1-18-bcd6b5701992">my last story</a>:</p><pre>type GenericLogger[T any] interface {<br>    WithField(string, string) T<br>    Info(string)<br>}</pre><p>This by itself is not yet very useful. There are easier ways to add a key-value string-pair to a logger and no logger (that I know of ) actually implements this interface. We also don’t need a new logging <a href="https://xkcd.com/927/">standard</a>. If we wanted to use e.g- <a href="https://github.com/sirupsen/logrus">logrus</a> we’d have to do something like this:</p><pre>type GenericLogger[T any, FIELD map[string]interface{}] interface{<br>    WithFields(M) T<br>    Info(string)<br>}</pre><p>This may actually be implemented by the logrus logger, if we add the self-referencing part. However, let’s consider using this in an actual struct, like a handler of some kind:</p><pre>type MessageHandler[T GenericLogger[T], FIELD map[string]interface{}] struct {<br>    logger GenericLogger[T, FIELD]<br>}<br></pre><p>As you can see, in order to use this logger in a struct, we need to make our struct generic, and that’s just for a logger. If the MessageHandler itself was handling generic messages, that would turn into a third type parameter!</p><p>And there isn’t even a way to assign this to a variable with generics as of now. So, even though it is awesome that we could represent this logger with an interface, I actually recommend against doing so. And my <a href="https://github.com/uber-go/zap">favorite log lib (zap)</a>, couldn’t even be represented by it due to the nature of its fields.</p><h3>The Ugly</h3><p>When I played around with generics, I stumbled over the missing support for introducing new generic parameters in methods. While that might have good reasons, it does require some workarounds. Let’s imagine we want to reduce a map to an int. We would ideally do this by using a method that returns a new generic parameter and then we can simply provide the map reduce function.</p><p>So what do we do when we still want to reduce that map in a generic fashion? Since there is no method, let’s create a method crabwise:</p><pre>type GenericMap[KEY comparable, VALUE any] map[KEY]VALUE</pre><pre>func (g GenericMap[KEY, VALUE]) Values() []VALUE {<br> values := make([]VALUE, len(g))<br> for _, v := range g {<br>  values = append(values, v)<br> }<br> return values<br>}</pre><pre>func Reduce[KEY comparable, VALUE any, RETURN any](g GenericMap[KEY, VALUE], callback func(RETURN, KEY, VALUE) RETURN) RETURN {<br> var r RETURN<br> for k, v := range g {<br>     r = callback(r, k, v)<br> }<br> return r<br>}</pre><p>As you can see, the GenericMap becomes the first parameter or our Reduce function. In this case you could use any kind of map as first parameter, instead of the GenericMap. The point I want to make, however, is, that it would be great if this method itself was part of the GenericMap. And even though it isn’t, we can still emulate that behavior. Overall, I will likely still use this pattern in some use-cases, even though it is in fact, ugly.</p><h3>The REALLY Ugly</h3><p>Sometimes you might want to make use of a factory pattern, which provides you something like, let’s say, DataProviders. You might want to get a provider on endpoints you dynamically register. So you could do something like that:</p><pre>type DataProviderFactory struct {<br>    dataProviders map[providerKey]any<br>}</pre><pre>func ProviderByName[MODEL Model](factory *DataProviderFactory, name string) (DataProvider[MODEL], bool) {<br>        var m MODEL<br>    prov, has := factory.dataProviders[providerKey{name: name, typ: reflect.TypeOf(m)}]<br>    if !has {<br>       return nil, false<br>    }<br>    return prov.(DataProvider[MODEL]), true <br>}</pre><pre>func RegisterProvider[MODEL Model](factory *DataProviderFactory, name string, p DataProvider[MODEL]) {<br>    var m MODEL<br>    factory.dataProviders[providerKey{name: name, typ: reflect.TypeOf(m)}] = p <br>}</pre><p>While this works, and while it might be useful, it is UGLY. First of all, it combines The Ugly with something even more ugly, which is reflection.</p><p>While technically this should be type safe, due to our composite key with name and the reflection type, it is still ugly. I would be very torn about whether I wanted to put this anywhere near production code.</p><h3>Conclusion</h3><p>While I like generics, I think it will be hard to strike a balance, especially in the beginning. So we need to make sure to keep in mind why they exist, and in what cases we should use them, and when we should avoid them!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e9fa2520e76" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/golang-1-18-generics-the-good-the-bad-the-ugly-5e9fa2520e76">golang 1.18+ generics: The Good, The Bad, The Ugly.</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self referencing interfaces in golang 1.18]]></title>
            <link>https://medium.com/swlh/self-referencing-interfaces-in-golang-1-18-bcd6b5701992?source=rss-2f154a981138------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcd6b5701992</guid>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[golang-development]]></category>
            <category><![CDATA[interface-design]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Michael Ernst]]></dc:creator>
            <pubDate>Fri, 17 Dec 2021 23:41:42 GMT</pubDate>
            <atom:updated>2021-12-17T23:41:42.186Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>I absolutely love structural typing ( which might be referred to as duck typing, but has some slight technical differences ). But there has always been one thing that I wished I could do, but couldn’t, till generics came into the picture!</p><p>The <a href="https://go.dev/blog/go1.18beta1">first beta of go1.18 was released some days ago</a> and I took it out for a spin since then. And it works just as expected and it is fast! It will save me from a lot of copying, even within a single project. ( check <a href="https://github.com/mier85/rcu">my attempt of generics Read-Copy-Update maps can can be found here</a> )</p><h3>The Problem</h3><p>But let’s get back to the problem that has annoyed me ever since I started using golang. Let’s imagine we have the following interface:</p><pre>type Logger interface {<br>    WithField(name, value string) Logger<br>    Info(message string)<br>}</pre><p>It is a very easy logger that you can add fields to and it returns itself. We don’t really need generics for it. But without them, we need to be aware of the interface itself, which effectively breaks the<a href="https://go.dev/tour/methods/10"> implicit interfacing</a>. As you can see we need to return Logger from WithField in order to implement the interface, which tightly couples our package to the package that defined the interface:</p><pre>type MyLogger struct {<br>}</pre><pre>func (m *MyLogger) WithField(string, string) Logger {<br> ...<br>}</pre><pre>func (m *MyLogger) Info(string) {<br>}</pre><h3>The Solution</h3><p>When trying to implement this with generics, the first straight forward idea would be to implement something like this:</p><pre>type GenericLogger[T any] interface {<br>    WithField(string, string) T<br>    Info(string)<br>}</pre><p>However, if you take a close look, this by itself is not exactly what we need yet. What we return is T which can be any but which is actually not GenericLogger! We are also not allowed to refer to the own interface here</p><p>We need to make sure that T is actually the type that we want to implement. The interface is sufficient to do this, but there is something we need to do when actually using it:</p><pre>func DoStuff[T GenericLogger[T]](t T) {<br>    t.WithField(&quot;go&quot;, &quot;1.18&quot;).Info(&quot;is awesome&quot;)<br>}</pre><p>Reading this is surely something you need to get used to first, but it is great that it works. What’s happening is basically that we accept a type T which needs to implement GenericLogger[T]. So at this point we basically recursively tell the GenericLogger that it itself is the generic object that shall be returned.</p><p><a href="https://gotipplay.golang.org/p/71m5yxV7ktd">Try it on playground</a>!</p><h3>Conclusion</h3><p>Go was already powerful before but I believe that thanks to generics there will be a new spark of interest. By getting less verbose we will be able to focus more on writing business logic and it helps go to be used in even more areas.</p><p>Structural typing, as one of go’s core strengths (IMHO), will also be more powerful.</p><p>I am looking forward to the release so I can use that in production!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9v2Om1w6e9B4FEKgbfSvOw.jpeg" /></figure><p>Notes:</p><p>Thanks to <a href="https://christophberger.com/">Christoph Berger</a> who <a href="https://github.com/golang/go/issues/28254#issuecomment-996822778">pointed out to me how we can make use of generics this way</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcd6b5701992" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/self-referencing-interfaces-in-golang-1-18-bcd6b5701992">Self referencing interfaces in golang 1.18</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The new Generics proposal tested]]></title>
            <link>https://medium.com/swlh/the-new-generics-proposal-tested-b9bd24f86547?source=rss-2f154a981138------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9bd24f86547</guid>
            <category><![CDATA[hands-on]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[proposal]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Michael Ernst]]></dc:creator>
            <pubDate>Thu, 18 Jun 2020 22:03:45 GMT</pubDate>
            <atom:updated>2021-12-20T08:16:30.465Z</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*g4ECiJ5gMg9IuRZ4CY1CTA.png" /></figure><p><strong><em>Disclaimer: this article is about how generics were supposed to look like a while ago and the code samples in here do not work with current versions of generics. However the concept remains same.</em></strong></p><p><a href="https://jaxenter.com/golang-dev-survey-171243.html">As many Go-developers, I also often wished for generics</a>. It’s not like I need them everyday, but occassionally, when writing libs and/or dealing with data structures, or when trying to solve something just a little more elegantly… I really want them.</p><p>So when reading <a href="https://blog.golang.org/generics-next-step">https://blog.golang.org/generics-next-step</a> I was thrilled that the proposal keeps getting refined and clearer ( also happy about the contract idea being dropped ).</p><p>So I actually went and gave it a try. So here I will tell you about a problem I just encountered literally a week ago, and how I solved it back then. Afterwards I will tell you what I’d do with the new generics at my disposal, and what I actually tested with the go2go tool.</p><h4>Why do we even need generics? The current situation!</h4><p>Last week was one of these days where I wanted to solve a simple problem: Render a table, using an interface to get my data. Not having generics, I had no choice but using our good friendinterface{} for defining the DataProvider interface:</p><pre>type DataProvider interface {<br>   Items() (interface{}<strong>, </strong>error)<br>}</pre><p>An implementation of the interface would look like this:</p><pre>type FileProvider struct {}<br><br>func (f FileProvider) Items() (interface{}<strong>, </strong>error) {<br>   return []File{<br>      {<br>         Name: &quot;foo.bar&quot;<strong>,<br>      </strong>}<strong>,<br>   </strong>}<strong>, </strong>nil<br>}</pre><p>When new to go, we would immediately wonder why an interface{} is used here instead of[]interface{} as we want to get a list of objects. If we want to return a list of interfaces, we would need to explicitly cast each element to an interface{}, and also we wouldn’t win much.</p><p>However with interface{} as return value, we face a multitude of problems:</p><ul><li>Are we sure that we really use a list here? There is no compile-time safety</li><li>If we want to get single elements from that list, without knowing the type, we can only use reflection: <a href="https://go-proverbs.github.io/">and we also don’t really want that.</a></li><li>It gets even more complicated when we want to write a generic parser which will give you single objects, which you ideally want to have as objects.</li></ul><p>A DataProvider is only the first part of the puzzle, what I really wanted is a renderer for the table, a generic http handler which uses the DataProvider to provide a list of items, as well as a generic http client which parses the list, and makes them available as File again for the table to render the fields. Really a lot of moving parts:</p><pre>func (r RestDataSource) GetItems() ([]model.Object<strong>, </strong>error) {<br>   resp<strong>, </strong>err := r.client.Get(r.getURL())<br>   if nil != err {<br>      return nil<strong>, </strong>fmt.Errorf(&quot;failed getting items: %w&quot;<strong>, </strong>err)<br>   }<br>   defer resp.Body.Close()<br>   slice := reflect.MakeSlice(reflect.SliceOf(r.typ)<strong>, 0, 0</strong>)<br>   decodeTo := reflect.New(slice.Type()).Interface()<br>   err = json.NewDecoder(resp.Body).Decode(&amp;decodeTo)<br>   if nil != err {<br>      return nil<strong>, </strong>fmt.Errorf(&quot;failed decoding json answer: %w&quot;<strong>, </strong>err)<br>   }<br>   target := reflect.ValueOf(decodeTo).Elem()<br>   objects := make([]model.Object<strong>, </strong>target.Len())<br>   for i := <strong>0; </strong>i &lt; target.Len()<strong>; </strong>i++ {<br>      obj := target.Index(i)<br>      objects[i] = NewDefaultObject(r.meta<strong>, </strong>obj)<br>   }<br>   return objects<strong>, </strong>nil<br>}</pre><p>Then last but not least, when I actually had my list of Object, which were internally File I still needed to render them, and there again I needed a type cast:</p><pre>table := elements.NewTable(fileProvider<strong>, </strong>elements.WithFieldRenderer(&quot;Name&quot;<strong>, </strong>func(obj model.Object<strong>, </strong>fieldValue interface{}<strong>, </strong>wr io.Writer) {<br>   fs := obj.Raw().(File)<br>   fmt.Fprintf(wr<strong>, </strong>`&lt;a href=&quot;%s&quot;&gt;&lt;img style=&quot;width:100px;height:100px;&quot; src=&quot;%s&quot; /&gt;%s&lt;/a&gt;`<strong>,</strong>&quot;/img/&quot;+fs.ID<strong>, </strong>&quot;/img/&quot;+fs.ID<strong>, </strong>fs.Name)<br>}))</pre><h4>How would generics help here?</h4><p>With generics, we will have type-safety and even more though, we can access the object without casting it first. So let’s see what we can do with the generics as proposed recently. First off, we want to have our data source:</p><pre>type DataSource(type T Object) interface {<br>    Data() ([]T, error)<br>}</pre><p>As we can see, the object that we will work on is not defined just yet, other than that it should implement the interface Object .</p><p>So to implement this interface, rather than returning an abstract type, we can just go ahead and return the actual type!</p><pre>type FileItemProvider struct {}<br><br>func (FileItemProvider) Data() ([]FileItem, error) {<br>    return []File{{ID:&quot;foo&quot;,Name:&quot;bar&quot;}}, nil<br>}</pre><p>So when defining the table which needs the data source, we also define that on a generic type:</p><pre>type Table(type T Object) struct {<br>    source DataSource(T)<br>    renderers map[string]func(T, io.Writer)<br>}</pre><p>So the table wants a DataSource with the same type and renderes with the same type. Now let’s see how a constructor for that could look like:</p><pre>func NewTable(type T Object)(source DataSource(T), options ...func(t *Table(T))) *Table(T) {<br>    table := &amp;Table(T){<br>        source: source,<br>        renderers: make(map[string]func(T, io.Writer)),<br>    }<br>    for _, option := range options {<br>        option(table)<br>    }<br>    return table<br>}</pre><p>Not only do we have the generic type for the constructor itself, but even for the funtional parameters:</p><pre>func WithRenderer(type T Object)(name string, fn func(T, io.Writer)) func(t *Table(T)) {<br>    return func (t *Table(T)) {<br>        t.renderers[name] = fn<br>    }<br>}</pre><p>So when we actually want to create the table, all we need to do is giving it the concrete type:</p><pre>table := NewTable(FileItem)(FileItemProvider{}, WithRenderer(&quot;Name&quot;, func(item FileItem, writer io.Writer) {<br>fmt.Fprintf(writer, `&lt;a href=&quot;%s&quot;&gt;&lt;img style=&quot;width:100px;height:100px;&quot; src=&quot;%s&quot; /&gt;%s&lt;/a&gt;`, &quot;/img/&quot;+item.ID, &quot;/img/&quot;+item.ID, item.Name)<br>  }))</pre><p>So we have the provider with static types, we have the functional parameters, and we can even access each individual type without a single type cast. We do not need reflection at all, as we can simply work with the concrete or generic types.</p><h4>Conclusion</h4><p>Go is getting more popular as we speak ( <a href="https://www.edureka.co/blog/top-10-programming-languages/">https://www.edureka.co/blog/top-10-programming-languages/</a> ) , jobs are getting easier to find, even in Germany. But I’d say it will peak next year, when generics are finally becoming a thing.</p><p>Whenever I faced problems like described before, I fancied Java or C# and wished my current project was written in it, even though I love Go. I kept thinking about better ways to solve the problems, but there weren’t any. I faced issues like that professionally and in personal projects, and really can’t wait to see them incorporate it into the language!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9bd24f86547" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/the-new-generics-proposal-tested-b9bd24f86547">The new Generics proposal tested</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>