Go : My thoughts for Go lang Interfaces

In many other languages go lang also supports interface but in some awkard way. You just create interfaces like Java or in C# but you do not actually implement those interfaces with a keyword like implements or with two dots like in C#. Instead , you create a struct and that struct implement function that is defined in interface with the same exact signature . Then this struct automatically is implementing that interfaces according to Go lang. So go lang does not provide you a keyword to implement interfaces, just let you write your own code and assume which struct implements which interfaces. It popped up a question in my mind , ok then how I can exactly know which struct implements which interfaces ? By just looking at the functions that the struct has ?. It seems like that is the only way. I’ve just started getting used to go lang but it really differs from any other languages in the manner of syntax and all other things. So far , to be honest I did not really like the go. But it amazed me with routines. They have just 2Kb memory foot print and they are so fast. So for CPU intensive services, it might be good choice to go with.

So I leave here a code snippet that includes a custom Struct that implements Writer Interface and read data from ozenoglu.com and print it out.

package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

type logWriter struct {
}

func main() {
	resp, err := http.Get("http://ozenoglu.com")
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	} else {
		lw := logWriter{}
		io.Copy(lw, resp.Body)
	}

}

func (logWriter) Write(bs []byte) (int, error) {
	fmt.Println(string(bs))
	fmt.Println("Just wrote many bytes ", len(bs))
	return len(bs), nil
}

Leave a Reply

Your email address will not be published. Required fields are marked *