<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Posts on Golang</title><link>https://golang.k5kc.com/post/</link><description>Recent content in Posts on Golang</description><generator>Hugo -- gohugo.io</generator><language>en-us</language><lastBuildDate>Mon, 17 Aug 2020 00:16:00 +0530</lastBuildDate><atom:link href="https://golang.k5kc.com/post/index.xml" rel="self" type="application/rss+xml"/><item><title>Defining gRPC service</title><link>https://golang.k5kc.com/2020/08/17/8.generating-client-server-code/</link><pubDate>Mon, 17 Aug 2020 00:16:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/17/8.generating-client-server-code/</guid><description>Next we need to generate the gRPC client and server interfaces from our .proto service definition. We do this using the protocol buffer compiler protoc with a special gRPC Go plugin.
For simplicity, we&amp;rsquo;ve provided a bash script that runs protoc for you with the appropriate plugin, input, and output (if you want to run this by yourself, make sure you&amp;rsquo;ve installed protoc and followed the gRPC-Go installation instructions first):</description></item><item><title>Concurrency and Parallelism</title><link>https://golang.k5kc.com/2020/08/16/0.concurrency-and-parallelism/</link><pubDate>Sun, 16 Aug 2020 00:00:00 +0000</pubDate><guid>https://golang.k5kc.com/2020/08/16/0.concurrency-and-parallelism/</guid><description>Concurrency The composition of independently executing tasks. Applied when dealing with handling lots of things at once. The focus is on how to structure a solution to solve a problem which may or may not be solved in a parallel manner. Concurrency is a way to structure a program by breaking it into pieces that can be executed independently. Communication is the means to coordinate the independent executions. Go supports concurrency.</description></item><item><title>Building a gRPC Client in Go</title><link>https://golang.k5kc.com/2020/08/16/10.building-grpc-client/</link><pubDate>Sun, 16 Aug 2020 00:19:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/10.building-grpc-client/</guid><description>In this section, we&amp;rsquo;ll look at creating a Go client for our RouteGuide service. You can see our complete example client code in grpc-go/examples/route_guide/client/client.go.
Creating a stub To call service methods, we first need to create a gRPC channel to communicate with the server. We create this by passing the server address and port number to grpc.Dial() as follows:
conn, err := grpc.Dial(*serverAddr) if err != nil { ... } defer conn.</description></item><item><title>My VS Code Congig for Go</title><link>https://golang.k5kc.com/2020/08/16/10.vs-code-settings-for-go/</link><pubDate>Sun, 16 Aug 2020 00:19:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/10.vs-code-settings-for-go/</guid><description>{ &amp;#34;go.lintTool&amp;#34;: &amp;#34;golangci-lint&amp;#34;, &amp;#34;go.formatTool&amp;#34;: &amp;#34;goimports&amp;#34;, &amp;#34;go.useLanguageServer&amp;#34;: true, &amp;#34;go.lintOnSave&amp;#34;: &amp;#34;package&amp;#34;, &amp;#34;go.vetOnSave&amp;#34;: &amp;#34;package&amp;#34;, &amp;#34;go.vetFlags&amp;#34;: [ &amp;#34;-all&amp;#34;, &amp;#34;-shadow&amp;#34; ] }</description></item><item><title>Building a gRPC Server in Go</title><link>https://golang.k5kc.com/2020/08/16/9.building-grpc-server/</link><pubDate>Sun, 16 Aug 2020 00:18:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/9.building-grpc-server/</guid><description>Let’s start off by defining a really simple gRPC server in Go. Once we have a simple server up and running we can set about creating a gRPC client that will be able to interact with it.
We will start off by writing the logic within our main function to listen on a port for incoming TCP connections:
main.go
package main import ( &amp;#34;log&amp;#34; &amp;#34;net&amp;#34; ) func main() { lis, err := net.</description></item><item><title>Create greet package</title><link>https://golang.k5kc.com/2020/08/16/9.go-ides-and-plugins/</link><pubDate>Sun, 16 Aug 2020 00:18:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/9.go-ides-and-plugins/</guid><description>Most main editors have some support for Go. Check the full list of IDEs and Plugins for Go on the official Go Wiki.
Though many editors support Go, they do not offer the same level of features and integrations.
These are things you might look for when considering an editor, from the most basic to the more advanced use cases. Keep in mind people tend to have different opinions here, so this is just a list to let you know some of what is possible, value the ones you care about most:</description></item><item><title>Cobra - Create CLI in Go</title><link>https://golang.k5kc.com/2020/08/16/1.setup-cobra/</link><pubDate>Sun, 16 Aug 2020 00:17:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/1.setup-cobra/</guid><description>Golang for CLI Go is the perfect language to develop command line applications. Go has a few advantages that really set it apart from other languages:
Single binary Very fast execution time, no interpreter needed Go is awesome! Cross platform support Command line based applications are nearly as old as computing itself but this doesn’t mean that they haven’t evolved. Traditional cli applications used flags to manage the different behaviors an application could perform.</description></item><item><title>Create the first test for your program</title><link>https://golang.k5kc.com/2020/08/16/8.first-go-test/</link><pubDate>Sun, 16 Aug 2020 00:17:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/8.first-go-test/</guid><description>The convention in Go is to put unit tests alongside the code that they test rather than in a different directory. This has the advantage of giving a very visible way of seeing what has tests and what doesn&amp;rsquo;t. All test files are named *_test.go; anything named that way will not be added to the final binary, but will be taken into account by go test.
Create a file main_test.go and add the following code:</description></item><item><title>Create your first Go program</title><link>https://golang.k5kc.com/2020/08/16/7.first-go-program/</link><pubDate>Sun, 16 Aug 2020 00:16:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/7.first-go-program/</guid><description>Lets write our first hello world program.
(1) Create a src directory in $GOPATH, which is /root/gowork in my system:
# mkdir src # tree . └── src 1 directory, 0 files (2) Since Go organizes source code using &amp;ldquo;package&amp;rdquo; concept , and every &amp;ldquo;package&amp;rdquo; should occupy a distinct directory, I create a greet directory in src:
Create a directory in your workspace:
mkdir -p $GOPATH/src/github.com/&amp;lt;your_user&amp;gt;/hello cd $GOPATH/src/github.com/&amp;lt;your_user&amp;gt;/hello touch main.go Open your favorite editor, and add the following to main.</description></item><item><title>Defining gRPC service</title><link>https://golang.k5kc.com/2020/08/16/7.defining-service/</link><pubDate>Sun, 16 Aug 2020 00:16:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/7.defining-service/</guid><description>Our first step (as you&amp;rsquo;ll know from the quick start) is to define the gRPC service and the method request and response types using protocol buffers. You can see the complete .proto file in examples/route_guide/routeguide/route_guide.proto.
To define a service, you specify a named service in your .proto file:
service RouteGuide { ... } Then you define rpc methods inside your service definition, specifying their request and response types. gRPC lets you define four kinds of service method, all of which are used in the RouteGuide service:</description></item><item><title>Detect Data Race</title><link>https://golang.k5kc.com/2020/08/16/6.detect-data-race/</link><pubDate>Sun, 16 Aug 2020 00:15:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/6.detect-data-race/</guid><description>&amp;ldquo;Data race&amp;rdquo; is a common but notorious issue in concurrency programs. sometimes it is difficult to debug and reproduce, especially in some big system, so this will make people very frustrated. Thankfully, the Go toolchain provides a race detector (now only works on amd64 platform.) which can help us quickly spot and fix this kind of issue, and this can save our time even lives!
Take the following classic &amp;ldquo;data race&amp;rdquo; program as an example:</description></item><item><title>Installing some common tools</title><link>https://golang.k5kc.com/2020/08/16/6.install-common-go-tools/</link><pubDate>Sun, 16 Aug 2020 00:15:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/6.install-common-go-tools/</guid><description>Use go get to download packages and their dependencies, then install them:
go get github.com/golang/lint/golint \ golang.org/x/tools/cmd/goimports Golint looks for common code style mistakes. Golint makes suggestions for many of the mechanically checkable items listed in Effective Go and the CodeReviewComments wiki page.
goimports formats your code correctly (it&amp;rsquo;s a drop-in replacement for gofmt) and also removes any unused imports. It will also try to resolve imports that haven&amp;rsquo;t been added to the imports definition.</description></item><item><title>Need not close every channel</title><link>https://golang.k5kc.com/2020/08/16/need-not-close-every-channel/</link><pubDate>Sun, 16 Aug 2020 00:15:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/need-not-close-every-channel/</guid><description>You don&amp;rsquo;t need to close channel after using it, and it can be recycled automatically by the garbage collector. The following quote is from The Go Programming Language:
You needn&amp;rsquo;t close every channel when you&amp;rsquo;ve finished with it. It&amp;rsquo;s only necessary to close a channel when it is important to tell the receiving goroutines that all data have been sent. A channel that the garbage collector determines to be unreachable will have its resources reclaimed whether or not it is closed.</description></item><item><title>nil channel VS closed channel</title><link>https://golang.k5kc.com/2020/08/16/nil-channel-vs-closed-channel/</link><pubDate>Sun, 16 Aug 2020 00:15:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/nil-channel-vs-closed-channel/</guid><description>The zero value of channel type is nil, and the send and receive operations on a nil channel will always block. Check the following example:
package main import &amp;#34;fmt&amp;#34; func main() { var ch chan int go func(c chan int) { for v := range c { fmt.Println(v) } }(ch) ch &amp;lt;- 1 } The running result is like this:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send (nil chan)]: main.</description></item><item><title>Setting up gRPC</title><link>https://golang.k5kc.com/2020/08/16/6.grpc-setup/</link><pubDate>Sun, 16 Aug 2020 00:15:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/6.grpc-setup/</guid><description>The example code for our tutorial is in grpc/grpc-go/examples/route_guide. To download the example, clone the grpc-go repository by running the following command:
go get google.golang.org/grpc Then change your current directory to grpc-go/examples/route_guide:
cd $GOPATH/src/google.golang.org/grpc/examples/route_guide You also should have the relevant tools installed to generate the server and client interface code - if you don&amp;rsquo;t already, follow the setup instructions in the Go quick start guide.</description></item><item><title>Go - for ... range</title><link>https://golang.k5kc.com/2020/08/16/5.range/</link><pubDate>Sun, 16 Aug 2020 00:14:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/5.range/</guid><description>Intro for ... range clause can be used to iterate 5 types of variables: array, slice, string, map and channel, and the following sheet gives a summary of the items of for ... range loops:
Type 1st Item 2nd Item Array index value Slice index value String index (rune) value (rune) Map key value Channel value Example - Iterating on slice package main import &amp;#34;fmt&amp;#34; func main() { s := [] {1,2,3} for i,v := range s { fmt.</description></item><item><title>Mutex - Mutual Exclusion Lock</title><link>https://golang.k5kc.com/2020/08/16/5.mutex/</link><pubDate>Sun, 16 Aug 2020 00:14:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/5.mutex/</guid><description>Intro Mutexes let you synchronize data access by explicit locking, without channels. Sometimes it’s more convenient to synchronize data access by explicit locking instead of using channels. The Go standard library offers a mutual exclusion lock, sync.Mutex, for this purpose.
Example - Basic usage Here&amp;rsquo;s a basic example illustrating Lock and Unlock:
func main() { mutex := sync.Mutex{} mutex.Lock() go func() { mutex.Lock() // Wait for main to call Unlock fmt.</description></item><item><title>Protocol buffers</title><link>https://golang.k5kc.com/2020/08/16/5.protocol-buffers/</link><pubDate>Sun, 16 Aug 2020 00:14:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/5.protocol-buffers/</guid><description>Intro Protobuf (or Protocol Buffers) is a language-agnostic and platform-neutral serialization format invented at Google. Each protocol buffer message is a small logical record of information, containing a series of name-value pairs.
Unlike XML or JSON, here you first define the schema in a .proto file. They are a format like JSON but simpler, smaller, strictly typed, understandable only from the client to the server and faster to Marshall/Unmarshall. For example:</description></item><item><title>Some common Go commands that you should know</title><link>https://golang.k5kc.com/2020/08/16/5.common-go-commands/</link><pubDate>Sun, 16 Aug 2020 00:14:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/5.common-go-commands/</guid><description>go build (see below): builds / compiles your code into a binary or library go install (see below): the same as go build, plus installs binaries into $GOPATH/bin and libraries to $GOPATH/pkg go get: downloads source code and dependencies, then perform a go install go test (see below): compile and run tests in the given package(s) go vet: check code for common coding errors https://github.com/RHCloudServices/golang-intro</description></item><item><title>Create Go workspace</title><link>https://golang.k5kc.com/2020/08/16/4.setup-go-workspace/</link><pubDate>Sun, 16 Aug 2020 00:13:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/4.setup-go-workspace/</guid><description>Once the Go build environment is ready, the next step is to create workspace for development:
(1) Set up a new empty directory - This is where your projects can reside:
mkdir $HOME/gowork (2) Use a new environment variable $GOPATH to point it:
# cat /etc/profile ...... GOPATH=$HOME/gowork export GOPATH ...... If you are using bash or zsh, put the following in the respective file:
export GOPATH=$HOME/gowork The workspace should contain 3 subdirectories:</description></item><item><title>Go - Maps</title><link>https://golang.k5kc.com/2020/08/16/4.maps/</link><pubDate>Sun, 16 Aug 2020 00:13:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/4.maps/</guid><description>Intro Maps are somewhat similar to what other languages call “dictionaries” or “hashes”. A map maps keys to values.
Here are some points to look at:
Maps allows us to quickly access to an element/value using a unique key. Map keys must be unique because otherwise it can&amp;rsquo;t find the corresponding values/elements. The types of Map Keys and Values in Maps can be different. A Map Key must be a comparable type.</description></item><item><title>Go loop - break and continue</title><link>https://golang.k5kc.com/2020/08/16/4.loop-break-and-continue/</link><pubDate>Sun, 16 Aug 2020 00:13:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/4.loop-break-and-continue/</guid><description>Intro break will break out of a loop. It&amp;rsquo;s a way to stop looping.
continue will move on to the next iteration. Let&amp;rsquo;s see it in action.
Examples Example - break package main import &amp;#34;fmt&amp;#34; func main() { pow := make([]int, 10) for i := range pow { pow[i] = 1 &amp;lt;&amp;lt; uint(i) if pow[i] &amp;gt;= 16 { break } } fmt.Println(pow) // [1 2 4 8 16 0 0 0 0 0] } Example - continue package main import &amp;#34;fmt&amp;#34; func main() { pow := make([]int, 10) for i := range pow { if i%2 == 0 { continue } pow[i] = 1 &amp;lt;&amp;lt; uint(i) } fmt.</description></item><item><title>Wait for goroutines Using WaitGroups</title><link>https://golang.k5kc.com/2020/08/16/4.wait-groups/</link><pubDate>Sun, 16 Aug 2020 00:13:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/4.wait-groups/</guid><description>Syntax A sync.WaitGroup waits for a group of goroutines to finish.
var wg sync.WaitGroup wg.Add(2) go func() { // Do work wg.Done() }() go func() { // Do work wg.Done() }() wg.Wait() First the main goroutine calls Add to set the number of goroutines to wait for. Then two new goroutines run and call Done when finished. At the same time, Wait is used to block until these two goroutines have finished.</description></item><item><title>Why use gRPC?</title><link>https://golang.k5kc.com/2020/08/16/4.why-use-grpc/</link><pubDate>Sun, 16 Aug 2020 00:13:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/4.why-use-grpc/</guid><description>With gRPC we can define our service once in a .proto file and implement clients and servers in any of gRPC&amp;rsquo;s supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. We also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating.</description></item><item><title>Adding behaviour to any type using Type Aliasing</title><link>https://golang.k5kc.com/2020/08/16/7.adding-behaviour-to-client-types-using-type-aliasing/</link><pubDate>Sun, 16 Aug 2020 00:12:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/7.adding-behaviour-to-client-types-using-type-aliasing/</guid><description>To define methods on a type you don’t “own”, you need to define an alias for the type you want to extend:
package main import ( &amp;#34;fmt&amp;#34; &amp;#34;strings&amp;#34; ) type MyStr string func (s MyStr) Uppercase() string { return strings.ToUpper(string(s)) } func main() { fmt.Println(MyStr(&amp;#34;test&amp;#34;).Uppercase()) } http://www.golangbootcamp.com/book/methods</description></item><item><title>Attaching Method to any type</title><link>https://golang.k5kc.com/2020/08/16/attaching-method-to-any-type/</link><pubDate>Sun, 16 Aug 2020 00:12:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/attaching-method-to-any-type/</guid><description> We can attach methods to any type in Go. For e.g.
// Basic Types int string float64 // Bare Types array struct // ----------------------- // Do not use &amp;#34;Pointer Receivers&amp;#34; with below types since they already carry a pointer with themselves. // i.e. slice, map, chan, func // ----------------------- // Pointer Bearing Types slice map chan // Channels // We can also attach methods to: func</description></item><item><title>Challenges with gRPC</title><link>https://golang.k5kc.com/2020/08/16/3.grpc-challenges/</link><pubDate>Sun, 16 Aug 2020 00:12:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/3.grpc-challenges/</guid><description>Challenges with gRPC You should bear in mind that whilst gRPC does allow you to utilize these newer bits of technology, it is more challenging prototyping a gRPC service due to the fact that tools like the Postman HTTP client cannot be used in order to easily interact with your exposed gRPC service.
You do have options that make this possible, but it’s not something that’s readily available natively. There are options to use tools such as envoy to reverse proxy standard JSON requests and transcode them into the right data format but this is an additional dependency that can be tricky to set up for simple projects.</description></item><item><title>Code Organization</title><link>https://golang.k5kc.com/2020/08/16/6.code-organization/</link><pubDate>Sun, 16 Aug 2020 00:12:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/6.code-organization/</guid><description>Methods can be defined on any file in the package, but my recommendation is to organize the code as shown below:
Define constants Define vars Define interface Define struct Implementation of methods on struct Example:
package models // list of packages to import import ( &amp;#34;fmt&amp;#34; ) // list of constants const ( ConstExample = &amp;#34;const before vars&amp;#34; ) // list of variables var ( ExportedVar = 42 nonExportedVar = &amp;#34;so say we all&amp;#34; ) type Fly interface { Fly() string } // Main type(s) for the file, // try to keep the lowest amount of structs per file when possible.</description></item><item><title>Go - for loop</title><link>https://golang.k5kc.com/2020/08/16/3.for-loop/</link><pubDate>Sun, 16 Aug 2020 00:12:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/3.for-loop/</guid><description>Go has only one looping construct, the for loop. The basic for loop looks as it does in C or Java, except that the ( ) are gone (they are not even optional) and the { } are required. As in C or Java, you can leave the pre and post statements empty.
for init; condition; post { } Examples Example - Go loop for j := 7; j &amp;lt;= 9; j++ { fmt.</description></item><item><title>Go - select</title><link>https://golang.k5kc.com/2020/08/16/3.select/</link><pubDate>Sun, 16 Aug 2020 00:12:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/3.select/</guid><description>Syntax
The select statement waits for multiple send or receive operations simultaneously.
// Blocks until there&amp;#39;s data available on ch1 or ch2 select { case &amp;lt;-ch1: fmt.Println(&amp;#34;Received from ch1&amp;#34;) case &amp;lt;-ch2: fmt.Println(&amp;#34;Received from ch2&amp;#34;) } The statement blocks as a whole until one of the operations becomes unblocked. If several cases can proceed, a single one of them will be chosen at random. Send and receive operations on a nil channel block forever.</description></item><item><title>Golang Slices</title><link>https://golang.k5kc.com/2020/08/16/3.slices/</link><pubDate>Sun, 16 Aug 2020 00:12:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/3.slices/</guid><description>Intro A slice in Golang is an abstraction that sits on top of an array. An array normally has a set size and must be initialised with a size. A slice is a little more like an array in javascript or an ArrayList in Java.
A slice is a descriptor of an array segment. It consists of a pointer to the array, the length of the segment, and its capacity (the maximum length of the segment).</description></item><item><title>Implement Sort Interface</title><link>https://golang.k5kc.com/2020/08/16/sort/</link><pubDate>Sun, 16 Aug 2020 00:12:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/sort/</guid><description>sort package defines an interface whose name is Interface:
type Interface interface { // Len is the number of elements in the collection. Len() int // Less reports whether the element with // index i should sort before the element with index j. Less(i, j int) bool // Swap swaps the elements with indexes i and j. Swap(i, j int) } For slice, or any other collection types, provided that it implements the Len(), Less and Swap functions, you can use sort.</description></item><item><title>Inheritance and Composition in GO</title><link>https://golang.k5kc.com/2020/08/16/3.inheritance-and-composition/</link><pubDate>Sun, 16 Aug 2020 00:12:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/3.inheritance-and-composition/</guid><description>Structs can &amp;ldquo;inherit&amp;rdquo; from other structs by a method known as embeding. Here is a simple example:
package main import ( &amp;#34;fmt&amp;#34; ) type a struct { Name string } //embeds a value of type a type b struct { a } //embeds a pointer to an a type c struct { *a } func main() { a := a{Name: &amp;#34;Janeway&amp;#34;} fmt.Println(a.Name) b := &amp;amp;b{a: a} fmt.Println(b.Name) c := &amp;amp;c{a: &amp;amp;a} fmt.</description></item><item><title>Method receiver vs Pointer receiver</title><link>https://golang.k5kc.com/2020/08/16/5.method-receiver-vs-pointer-receiver/</link><pubDate>Sun, 16 Aug 2020 00:12:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/5.method-receiver-vs-pointer-receiver/</guid><description>Struct values when used as method receivers are exactly that values and so are a shallow copy of the value allocated a new portion of memory. The effects are not observed outside of the method as there are no references to the new value and so it is garbaged collected.
Pointer receivers allow mutation of what the pointer points to. Your function is recieving a pointer to the same address in memory even in the function stackframe.</description></item><item><title>Methods in GO</title><link>https://golang.k5kc.com/2020/08/16/4.methods/</link><pubDate>Sun, 16 Aug 2020 00:12:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/4.methods/</guid><description>Intro We have already seen golang functions. Now the question is:
what is the difference between a function and a method in Go?
Answer is -
A method is a function that has a defined receiver, in OOP terms, a method is a function on an instance of an object.
Go doesnt have classes but structs, and we can add receiver methods on structs to add behaviour.
To add some behaviour to a struct you can have it be a method reciever.</description></item><item><title>Understanding the GOPATH environment variable</title><link>https://golang.k5kc.com/2020/08/16/3.understand-gopath/</link><pubDate>Sun, 16 Aug 2020 00:12:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/3.understand-gopath/</guid><description>The GOPATH environment variable lists places to look for Go code. It defines your workspace. It is likely the only environment variable you&amp;rsquo;ll need to set when developing Go code.
Official documentation:
How to Write Go Code: The GOPATH environment variable Command go: GOPATH environment variable Normally the GOPATH is set in your shell profile (one of ~/.bashrc, ~/.bash_profile, etc).
When you install packages and build binaries, the Go tool will look for source code in $GOPATH/src/ followed by a package import path in order to resolve dependencies.</description></item><item><title>Channels in Go</title><link>https://golang.k5kc.com/2020/08/16/2.channels/</link><pubDate>Sun, 16 Aug 2020 00:11:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/2.channels/</guid><description>Intro A go maxim or proverb is:
Do not communicate by sharing memory; instead, share memory by communicating.
So what is a channel?
A channel is a &amp;ldquo;typed&amp;rdquo; conduit (pipes) mechanism for goroutines to synchronize execution and communicate by passing values, using channel operator, &amp;lt;-. They are mechanism for communication between goroutines.
Syntax // can only be used to send float64s chan&amp;lt;- float64 // can only be used to receive ints &amp;lt;-chan int // can be used to send and receive values of type Dosa chan Dosa (The data flows in the direction of the arrow.</description></item><item><title>Go - Array</title><link>https://golang.k5kc.com/2020/08/16/2.array/</link><pubDate>Sun, 16 Aug 2020 00:11:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/2.array/</guid><description>Syntax In Go, the length is also a part of array type. So the following code declares an array:
var array [3]int while &amp;ldquo;var slice []int&amp;rdquo; defines a slice. Arrays cannot be resized.
Another way is to set the array entries as you declare the array:
func main() { a := [2]string{&amp;#34;hello&amp;#34;, &amp;#34;world!&amp;#34;} fmt.Printf(&amp;#34;%q&amp;#34;, a) } You can also use an implicit length when passing values to array using [...]:</description></item><item><title>Go Conditionals - switch</title><link>https://golang.k5kc.com/2020/08/16/2.switch/</link><pubDate>Sun, 16 Aug 2020 00:11:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/2.switch/</guid><description>Intro In addition to the switch keyword, a switch statement has cases. The switch statement switches on some case.
Example - No break required Compared to other programming languages (such as C), Go&amp;rsquo;s switch-case statement doesn&amp;rsquo;t need explicit &amp;ldquo;break&amp;rdquo;, and not have fall-though characteristic. Take the following code as an example:
package main import ( &amp;#34;fmt&amp;#34; ) func checkSwitch(val int) { switch val { case 0: case 1: fmt.Println(&amp;#34;The value is: &amp;#34;, val) } } func main() { checkSwitch(0) checkSwitch(1) } The output is:</description></item><item><title>Go Configuration - Environment variables</title><link>https://golang.k5kc.com/2020/08/16/2.go-environment-variables/</link><pubDate>Sun, 16 Aug 2020 00:11:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/2.go-environment-variables/</guid><description>Open up .profile or .zshrc or .bashrc depending on our OS and add/edit following:
#!/bin/bash # Specifies where the Go destribution is installed on the system. export GOROOT=/usr/local/go # Specifies top-level directory containing source code for all our Go projects. # Inside this directory, we need to create 3 more directories viz. &amp;#34;src&amp;#34;, &amp;#34;pkg&amp;#34; and &amp;#34;bin&amp;#34;. export GOPATH=~/adiwork/go # This directory is also known as Go Workspace. # &amp;#34;src&amp;#34; directory inside Workspace represents where all the Go source code will be stored.</description></item><item><title>gRPC vs Rest</title><link>https://golang.k5kc.com/2020/08/16/2.grpc-vs-rest/</link><pubDate>Sun, 16 Aug 2020 00:11:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/2.grpc-vs-rest/</guid><description>Whilst REST and gRPC are somewhat similar, there are some fundamental differences in how they work that you should be aware of.
gRPC utilizes HTTP/2 whereas REST utilizes HTTP 1.1 gRPC utilizes the protocol buffer data format as opposed to the standard JSON data format that is typically used within REST APIs. This provides us with strong schema and backward compatibility. With gRPC you can utilize HTTP/2 capabilities such as server-side streaming, client-side streaming or even bidirectional-streaming should you wish.</description></item><item><title>Interface in Go</title><link>https://golang.k5kc.com/2020/08/16/2.interface/</link><pubDate>Sun, 16 Aug 2020 00:11:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/2.interface/</guid><description>Intro We declare an Interface much like as we define a user defined type. Interfaces decouple different types from each other so we can create more maintainable programs.
More:
An Interface is a Protocol, a Contract.
Bigger the Interface the weaker the abstraction. &amp;ndash;&amp;gt; Rob Pike
It&amp;rsquo;s an abstract type. It doesn&amp;rsquo;t have any implementation. It only describes the expected behavior.
The opposite of Abstract Type is Concrete Type.
All the types in Go except Interface are of Concrete Type.</description></item><item><title>"go build" and "go install"</title><link>https://golang.k5kc.com/2020/08/16/go-build-vs-go-install/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/go-build-vs-go-install/</guid><description>Let&amp;rsquo;s tidy up the $GOPATH directory and only keep Go source code files left over:
# tree . ├── bin ├── pkg └── src ├── greet │ └── greet.go └── hello └── hello.go 5 directories, 2 files The greet.go is greet package which just provides one function:
# cat src/greet/greet.go package greet import &amp;#34;fmt&amp;#34; func Greet() { fmt.Println(&amp;#34;नमस्ते किंशुक!&amp;#34;) } While hello.go is a main package which takes advantage of greet and can be built into an executable binary:</description></item><item><title>"go get" command</title><link>https://golang.k5kc.com/2020/08/16/5.go-get-command/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/5.go-get-command/</guid><description>&amp;ldquo;go get&amp;rdquo; command is the standard way of downloading and installing packages and related dependencies.
The snippet above basically tells the compiler to import the crypto package available at the github.com/mattetti/goRailsYourself/crypto path. It doesn’t mean that the compiler will automatically pull down the repository, so where does it find the code?
You need to pull down the code yourself. The easiest way is to use the go get command provided by Go.</description></item><item><title>"nil slice" vs "nil map"</title><link>https://golang.k5kc.com/2020/08/16/nil-slice-vs-nil-map/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/nil-slice-vs-nil-map/</guid><description>Slice and map are all reference types in Go, and their default values are nil:
package main import &amp;#34;fmt&amp;#34; func main() { var ( s []int m map[int]bool ) if s == nil { fmt.Println(&amp;#34;The value of s is nil&amp;#34;) } if m == nil { fmt.Println(&amp;#34;The value of m is nil&amp;#34;) } } The result is like this：
The value of s is nil The value of m is nil When a slice&amp;rsquo;s value is nil, you could also do operations on it, such as append:</description></item><item><title>Accessing Map</title><link>https://golang.k5kc.com/2020/08/16/accessing-map/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/accessing-map/</guid><description>Map is a reference type which points to a hash table, and you can use it to construct a &amp;ldquo;key-value&amp;rdquo; database which is very handy in practice programming. E.g., the following code will calculate the count of every element in a slice:
package main import ( &amp;#34;fmt&amp;#34; ) func main() { s := []int{1, 1, 2, 2, 3, 3, 3} m := make(map[int]int) for _, v := range s { m[v]++ } for key, value := range m { fmt.</description></item><item><title>Adding multiple types to collection</title><link>https://golang.k5kc.com/2020/08/16/5.adding-multiple-types-to-collection/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/5.adding-multiple-types-to-collection/</guid><description>I would generally recommend avoiding this, but sometimes it could be neccessary. To add multiple types to a single map you must declare the map to take the interface type. The interface type is comparable to Object in Java. Everyhing is an interface.
package main import &amp;#34;fmt&amp;#34; func main(){ m := map[string]interface{}{ &amp;#34;test&amp;#34;:1, &amp;#34;test2&amp;#34;:&amp;#34;test&amp;#34;, } fmt.Println(m) s := []interface{}{ &amp;#34;test&amp;#34;, 2, } fmt.Println(s) }</description></item><item><title>Adding sugar - map, reduce and filter, etc to slice</title><link>https://golang.k5kc.com/2020/08/16/6.add-sugar-mapreducefilter-to-slice/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/6.add-sugar-mapreducefilter-to-slice/</guid><description>Golang prides itself on being a simple , pragmatic language and tried to avoid sugar that its creators feel are unnecessary. So lets add some map reduce functions ourselves to see what is involved:
package main import &amp;#34;fmt&amp;#34; type MyList []string // a custom type can be a builtin type if you want it to be func (ml MyList) Filter(f func(string) bool) []string { na := []string{} for _, v := range ml { if add := f(v); add { na = append(na, v) } } return na } func (ml MyList) Reduce(f func(prev, current string, index int) string) []string { na := []string{} for i, v := range ml { if i == 0 { na = append(na, f(&amp;#34;&amp;#34;, v, i)) } else { na = append(na, f(ml[i-1], v, i)) } } return na } func (ml MyList) Map(f func(val string) *string) []string { na := []string{} for _, v := range ml { mVal := f(v) if nil !</description></item><item><title>Buffered read</title><link>https://golang.k5kc.com/2020/08/16/buffered-read/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/buffered-read/</guid><description>bufio package provides buffered read functions. Let&amp;rsquo;s see an example:
(1) Create a test.txt file first:
cat test.txt Output:
abcd efg hijk lmn You can see test.txt contains 4 lines.
(2) See the following program:
package main import ( &amp;#34;bufio&amp;#34; &amp;#34;fmt&amp;#34; &amp;#34;io&amp;#34; &amp;#34;log&amp;#34; &amp;#34;os&amp;#34; ) func main() { f, err := os.Open(&amp;#34;test.txt&amp;#34;) if err != nil { log.Fatal(err) } r := bufio.NewReader(f) for { if s, err := r.ReadSlice(&amp;#39;\n&amp;#39;); err == nil || err == io.</description></item><item><title>Common Abbreviations Used In Go</title><link>https://golang.k5kc.com/2020/08/16/common-abbreviation/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/common-abbreviation/</guid><description>Following are some of the common Abbreviations used in Go standard libraries:
var s string // string var i int // index var num int // number var msg string // message var v string // value var val string // value var fv string // flag value var err error // error value var args []string // arguments var seen bool // has seen? var parsed bool // parsing ok?</description></item><item><title>Constants in Go</title><link>https://golang.k5kc.com/2020/08/16/2.constants/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/2.constants/</guid><description>Intro Constants are declared like variables, but with the const keyword. Constants can only be character, string, boolean, or numeric values and cannot be declared using the := syntax. An untyped constant takes the type needed by its context.
Example:
const Pi = 3.14 const ( StatusOK = 200 StatusCreated = 201 StatusAccepted = 202 StatusNonAuthoritativeInfo = 203 StatusNoContent = 204 StatusResetContent = 205 StatusPartialContent = 206 ) Constants belong to compile time.</description></item><item><title>Conversion between array and slice</title><link>https://golang.k5kc.com/2020/08/16/conversion-between-array-and-slice/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/conversion-between-array-and-slice/</guid><description>In Go, array is a fixed length of continuous memory with specified type, while slice is just a reference which points to an underlying array. Since they are different types, they can&amp;rsquo;t assign value each other directly. See the following example:
package main import &amp;#34;fmt&amp;#34; func main() { s := []int{1, 2, 3} var a [3]int fmt.Println(copy(a, s)) } Because copy only accepts slice argument, we can use the [:] to create a slice from array.</description></item><item><title>Create greet package</title><link>https://golang.k5kc.com/2020/08/16/4.create-greet-package/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/4.create-greet-package/</guid><description>mkdir src/greet Then create a new Go source code file (greet.go) in src/greet:
# cat src/greet/greet.go package greet import &amp;#34;fmt&amp;#34; func Greet() { fmt.Println(&amp;#34;नमस्ते किंशुक!&amp;#34;) } You can consider this greet directory provides a greet package which can be used by other programs.
(3) Create another package hello which utilizes the greet package:
# mkdir src/hello # cat src/hello/hello.go package main import &amp;#34;greet&amp;#34; func main() { greet.Greet() } You can see in hello.</description></item><item><title>Debugging</title><link>https://golang.k5kc.com/2020/08/16/debugging/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/debugging/</guid><description>No one can write bug-free code, so debugging is a requisite skill for every software engineer. Here are some tips about debugging Go programs:
(1) Print
Yes! Printing logs seems the easiest method, but it is indeed the most effective approach in most cases. Go has provided a big family of printing functions in fmt package, and using them neatly is an expertise you should grasp.
(2) Debugger
In some scenarios, maybe you need the specialized debugger tools to help you spot the root cause.</description></item><item><title>Decorate types to implement io.Reader interface</title><link>https://golang.k5kc.com/2020/08/16/decorate-types-to-implement-io-reader-interface/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/decorate-types-to-implement-io-reader-interface/</guid><description>The io package has provided a bunch of handy read functions and methods, but unfortunately, they all require the arguments satisfy io.Reader interface. See the following example:
package main import ( &amp;#34;fmt&amp;#34; &amp;#34;io&amp;#34; ) func main() { s := &amp;#34;Hello, world!&amp;#34; p := make([]byte, len(s)) if _, err := io.ReadFull(s, p); err != nil { fmt.Println(err) } else { fmt.Printf(&amp;#34;%s\n&amp;#34;, p) } } Compile above program and an error is generated:</description></item><item><title>Dependency Management - vendoring</title><link>https://golang.k5kc.com/2020/08/16/12.dependency-management-vendoring/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/12.dependency-management-vendoring/</guid><description>Google is well known to have an immense mono repo so go get works well for them. This is not the case with everyone else. By default go get pulls the master branch of the repo you point it at. When you do a go get it pulls in the required dependencies, this means there are issues with reproducibility. As of go 1.5 they looked to address some of the issues by introducing the vendor directory.</description></item><item><title>Error handling intro</title><link>https://golang.k5kc.com/2020/08/16/1.error-handling/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/1.error-handling/</guid><description>nil is a predeclared identifier like true, false, len(), int32, float64 etc.
Since it is a predeclared identifier, it can be used anywhere without importing any package.
nil value means that the value is not initialized yet.
It is similar to following identifiers in other languages:
null // JavaScript None // Python null // Java nil // Ruby The zero value of all pointer-based types in Go is nil. Following are the pointer-based types in Go:</description></item><item><title>Error handling intro</title><link>https://golang.k5kc.com/2020/08/16/2.error-interface/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/2.error-interface/</guid><description>Error is by far the most used interface in Go. lets have a look at it:
type error interface { Error() string } //The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error. So any type that implements the Error method is by default an error type. Some Examples:
package main import &amp;#34;fmt&amp;#34; type MyError string func (me MyError) Error() string{ return string(me) //cast it back to string } type MyOtherError struct{ Code int Message string } func (me MyOtherError) Error() string{ return fmt.</description></item><item><title>error vs errors</title><link>https://golang.k5kc.com/2020/08/16/error-vs-errors/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/error-vs-errors/</guid><description>Handling errors is a crucial part of writing robust programs. When scanning the Go packages, it is not rare to see APIs which have multiple return values with an error among them. For example:
func Open(name string) (*File, error)
Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.</description></item><item><title>Exporting name</title><link>https://golang.k5kc.com/2020/08/16/7.exported-names/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/7.exported-names/</guid><description>To export a name in Go, just make it&amp;rsquo;s first letter an uppercase letter. From within a package namespace you can refer to private functions and variables (starting with lower case) but from outside the package, you can only access the things exported from that package. Think public and private key word in Java.
//exported func MyPublicFunc(){ } //private func myPrivateFunc(){ }</description></item><item><title>Functional literals</title><link>https://golang.k5kc.com/2020/08/16/functional-literals/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/functional-literals/</guid><description>A functional literal just represents an anonymous function. You can assign functional literal to a variable:
package main import ( &amp;#34;fmt&amp;#34; ) func main() { f := func() { fmt.Println(&amp;#34;Hello, भारत！&amp;#34;) } f() } Or invoke functional literal directly (Please notice the () at the end of functional literal):
package main import ( &amp;#34;fmt&amp;#34; ) func main() { func() { fmt.Println(&amp;#34;Hello, भारत！&amp;#34;) }() } The above 2 programs both output &amp;ldquo;Hello, भारत！&amp;rdquo;.</description></item><item><title>Go - init function</title><link>https://golang.k5kc.com/2020/08/16/init-function/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/init-function/</guid><description>There is a init() function, as the name suggests, it will do some initialization work, such as initializing variables which may not be expressed easily, or calibrating program state. A file can contain one or more init() functions, as shown here:
package main import &amp;#34;fmt&amp;#34; var global int = 0 func init() { global++ fmt.Println(&amp;#34;In first Init(), global is: &amp;#34;, global) } func init() { global++ fmt.Println(&amp;#34;In Second Init(), global is: &amp;#34;, global) } func main() { fmt.</description></item><item><title>Go - Basic Data Type</title><link>https://golang.k5kc.com/2020/08/16/2.basic-data-types/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/2.basic-data-types/</guid><description>Following are the basic data types in Go:
Numeric // Integer Types uint8 // Unsigned 8-bit integers (0 to 255) uint16 // Unsigned 16-bit integers (0 to 65535) uint32 // Unsigned 32-bit integers (0 to 4294967295) uint64 // Unsigned 64-bit integers (0 to 18446744073709551615) int8 // Signed 8-bit integers (-128 to 127) int16 // Signed 16-bit integers (-32768 to 32767) int32 // Signed 32-bit integers (-2147483648 to 2147483647) int64 // Signed 64-bit integers (-9223372036854775808 to 9223372036854775807) // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // Floating Types float32 // IEEE-754 32-bit floating-point numbers float64 // IEEE-754 64-bit floating-point numbers complex64 // Complex numbers with float32 real and imaginary parts complex128 // Complex numbers with float64 real and imaginary parts // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // Other Numeric Types byte // same as uint8 rune // same as int32 uint // 32 or 64 bits int // same size as uint uintptr // an unsigned integer to store the uninterpreted bits of a pointer value Handling Overflows At compile time, a Go compiler can catch overflow errors.</description></item><item><title>Go - Data Type Intro</title><link>https://golang.k5kc.com/2020/08/16/1.data-types-intro/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/1.data-types-intro/</guid><description>There are following data types in Go:
Basic type: Numbers, strings, and booleans come under this category. Aggregate type: Array and structs come under this category. Reference type: Pointers, slices, maps, functions, and channels come under this * category. Interface type</description></item><item><title>Go - defer</title><link>https://golang.k5kc.com/2020/08/16/11.defer/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/11.defer/</guid><description>The defer statement is used to postpone a function call executed immediately before the surrounding function returns. The common uses of defer include releasing resources (i.e., unlock the mutex, close file handle.), do some tracing(i.e., record the running time of function), etc. E.g., an ordinary accessing global variable exclusively is like this:
var mu sync.Mutex var m = make(map[string]int) func lookup(key string) int { mu.Lock() v := m[key] mu.Unlock() return v } An equivalent but concise format using defer is as follow:</description></item><item><title>Go - literals</title><link>https://golang.k5kc.com/2020/08/16/10.literals/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/10.literals/</guid><description>literal means the value itself. Unlike variable, a literal doesn&amp;rsquo;t have a name.</description></item><item><title>Go - Mutability</title><link>https://golang.k5kc.com/2020/08/16/mutability/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/mutability/</guid><description>In Go, only constants are immutable. However because arguments are passed by value, a function receiving a value argument and mutating it, won’t mutate the original value.
package main import &amp;#34;fmt&amp;#34; type Artist struct { Name, Genre string Songs int } func newRelease(a Artist) int { a.Songs++ return a.Songs } func main() { me := Artist{Name: &amp;#34;Matt&amp;#34;, Genre: &amp;#34;Electro&amp;#34;, Songs: 42} fmt.Printf(&amp;#34;%s released their %dth song\n&amp;#34;, me.Name, newRelease(me)) fmt.Printf(&amp;#34;%s has a total of %d songs&amp;#34;, me.</description></item><item><title>Go - Named and Unnamed Types</title><link>https://golang.k5kc.com/2020/08/16/named-vs-unnamed-types/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/named-vs-unnamed-types/</guid><description>Types in Go are divided into 2 categories: named and unnamed. Besides predeclared types (such as int, rune, etc), you can also define named type yourself. E.g.:
type mySlice []int Unnamed types are defined by type literal. I.e., []int is an unnamed type.
According to Go spec, there is an underlying type of every type:
Each type T has an underlying type: If T is one of the predeclared boolean, numeric, or string types, or a type literal, the corresponding underlying type is T itself.</description></item><item><title>Go - Processing JSON object</title><link>https://golang.k5kc.com/2020/08/16/processing-json-object/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/processing-json-object/</guid><description>JSON is a commonly used and powerful data-interchange format, and Go provides a built-in json package to handle it. Let&amp;rsquo; see the following example:
package main import ( &amp;#34;encoding/json&amp;#34; &amp;#34;log&amp;#34; &amp;#34;fmt&amp;#34; ) type People struct { Name string age int Career string `json:&amp;#34;career&amp;#34;` Married bool `json:&amp;#34;,omitempty&amp;#34;` } func main() { p := &amp;amp;People{ Name: &amp;#34;Nan&amp;#34;, age: 34, Career: &amp;#34;Engineer&amp;#34;, } data, err := json.Marshal(p) if err != nil { log.Fatalf(&amp;#34;JSON marshaling failed: %s&amp;#34;, err) } fmt.</description></item><item><title>Go - Slice copy</title><link>https://golang.k5kc.com/2020/08/16/array-copy/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/array-copy/</guid><description>The definition of built-in copy function is here:
func copy(dst, src []Type) int
The copy built-in function copies elements from a source slice into a destination slice. (As a special case, it also will copy bytes from a string to a slice of bytes.) The source and destination may overlap. Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).
Let&amp;rsquo;s see a basic example in which source and destination slices aren&amp;rsquo;t overlapped:</description></item><item><title>Go - String</title><link>https://golang.k5kc.com/2020/08/16/3.string/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/3.string/</guid><description>In Go, string is an immutable array of bytes. So if created, we can&amp;rsquo;t change its value. E.g.:
package main func main() { s := &amp;#34;Hello&amp;#34; s[0] = &amp;#39;h&amp;#39; } The compiler will complain:
cannot assign to s[0]
To modify the content of a string, you could convert it to a byte array. But in fact, you do not operate on the original string, just a copy:
package main import &amp;#34;fmt&amp;#34; func main() { s := &amp;#34;Hello&amp;#34; b := []byte(s) b[0] = &amp;#39;h&amp;#39; fmt.</description></item><item><title>Go - Structs</title><link>https://golang.k5kc.com/2020/08/16/1.struct/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/1.struct/</guid><description>Intro A struct is a collection of fields/properties. You can define new types as structs or interfaces. If you are coming from an object-oriented background, you can think of a struct to be a light class that supports composition but not inheritance.
Structs are blueprints — They are fixed and created at compile-time, but struct values fill them in runtime..
It&amp;rsquo;s like a class in OOP languages. Groups related data in a single type.</description></item><item><title>Go - Type conversion</title><link>https://golang.k5kc.com/2020/08/16/4.type-conversion/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/4.type-conversion/</guid><description>The expression T(v) converts the value v to the type T. Some numeric conversions:
var i int = 42 var f float64 = float64(i) var u uint = uint(f) Or, put more simply:
i := 42 f := float64(i) u := uint(f) Go assignment between items of different type requires an explicit conversion which means that you manually need to convert types if you are passing a variable to a function expecting another type.</description></item><item><title>Go Conditinals - if else statement</title><link>https://golang.k5kc.com/2020/08/16/1.if-else/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/1.if-else/</guid><description>if Statement Simple if syntax The if statement looks as it does in C or Java, except that the ( ) are gone and the { } are required. Like for, the if statement can start with a short statement to execute before the condition. Variables declared by the statement are only in scope until the end of the if. Variables declared inside an if short statement are also available inside any of the else blocks.</description></item><item><title>Go functions</title><link>https://golang.k5kc.com/2020/08/16/8.functions/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/8.functions/</guid><description>A function can take zero or more typed arguments. The type comes after the variable name. Functions can be defined to return any number of values that are always typed.
package main import &amp;#34;fmt&amp;#34; func add(x int, y int) int { return x + y } func main() { fmt.Println(add(42, 13)) } Go Tour Functions example In the following example, instead of declaring the type of each parameter, we only declare one type that applies to both.</description></item><item><title>Go Packages and Import</title><link>https://golang.k5kc.com/2020/08/16/3.package/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/3.package/</guid><description>All package files, should be in the same (single) directory. i.e. all package source code files should be located in a one single directory. All files in a specific folder should belong to a one single package. It&amp;rsquo;s a convention, not a rule.
package clause can be used only once per file and it should be the first line in .go source file.
Package contains multiple Go files belonging to same folder.</description></item><item><title>Go Pointers</title><link>https://golang.k5kc.com/2020/08/16/pointers/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/pointers/</guid><description>Go has pointers, but no pointer arithmetic. Struct fields can be accessed through a struct pointer. The indirection through the pointer is transparent (you can directly call fields and methods on a pointer).
Note that by default Go passes arguments by value (copying the arguments), if you want to pass the arguments by reference, you need to pass pointers (or use a structure using reference values like slices (Section 4.2) and maps (Section 4.</description></item><item><title>Golang Collections Intro</title><link>https://golang.k5kc.com/2020/08/16/1.collections-intro/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/1.collections-intro/</guid><description>Golang has two main collection types.
maps.
arrays and slices</description></item><item><title>Goroutines - Go Coroutines</title><link>https://golang.k5kc.com/2020/08/16/1.goroutines/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/1.goroutines/</guid><description>Syntax A goroutine is a lightweight thread managed by the Go runtime.
go f(x, y, z) // notice go keyword starts a new goroutine running:
f(x, y, z) The evaluation of f, x, y, and z happens in the current goroutine and the execution of f happens in the new goroutine.
All goroutines in a single program share the same address space. So access to shared memory must be synchronized. The sync package provides useful primitives, although you won’t need them much in Go as there are other primitives.</description></item><item><title>gRPC Introduction</title><link>https://golang.k5kc.com/2020/08/16/1.grpc-intro/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/1.grpc-intro/</guid><description>So, before we dive in, we first need to understand what gRPC is, how it works and so on.
Definition - gRPC is a modern, open source remote procedure call (RPC) framework that can run anywhere
Remote Procedure Calls are something that we use within distributed systems that allow us to communicate between applications. More specifically, it allows us to expose methods within our application that we want other applications to be able to invoke.</description></item><item><title>How to build Go development environment</title><link>https://golang.k5kc.com/2020/08/16/how-to-build-go-development-environment/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/how-to-build-go-development-environment/</guid><description>Build Go development environment is always easy. Take Linux OS as an example (Because I work as a root user, so if you login as a non-root user, maybe you need sudo to execute some commands), what you should do is just download the binary package which matches your system from here, and uncompress it:
# wget https://storage.googleapis.com/golang/go1.6.2.linux-amd64.tar.gz # tar -C /usr/local/ -xzf go1.6.2.linux-amd64.tar.gz Now, there is an extra go directory under /usr/local.</description></item><item><title>Install Golang</title><link>https://golang.k5kc.com/2020/08/16/1.install-golang/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/1.install-golang/</guid><description>Installing using OS package manager You might use your package manager to install Go or install manually from the official release binaries. Either way should be easy.
Because the go tool is able to download code from remote repositories, it is often useful to have installed clients for the various supported version control systems. At the time of this writing, they are documented as: Bazaar, Git, Mercurial and Subversion.
They are not mandatory requirements, you might go a long way with just having git installed, and installing others later as required.</description></item><item><title>io.Reader interface</title><link>https://golang.k5kc.com/2020/08/16/io-reader-interfaces/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/io-reader-interfaces/</guid><description>io.Reader interface is a basic and very frequently-used interface:
type Reader interface { Read(p []byte) (n int, err error) } For every type who satisfies the io.Reader interface, you can imagine it&amp;rsquo;s a pipe. Someone writes contents into one end of the pipe, and you can use Read() method which the type has provided to read content from the other end of the pipe. No matter it is a common file, a network socket, and so on.</description></item><item><title>io.Writer interface</title><link>https://golang.k5kc.com/2020/08/16/io-writer-interface/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/io-writer-interface/</guid><description>The inverse of io.Reader is io.Writer interface:
type Writer interface { Write(p []byte) (n int, err error) } Compared to io.Reader, since you no need to consider io.EOF error, the process of Write method is simple:
(1) err == nil: All the data in p is written successfully;
(2) err != nil: The data in p is partially or not written at all.
Let&amp;rsquo;s see an example:
package main import ( &amp;#34;log&amp;#34; &amp;#34;os&amp;#34; ) func main() { f, err := os.</description></item><item><title>Method with struct and interface</title><link>https://golang.k5kc.com/2020/08/16/methods-with-struct-and-interface/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/methods-with-struct-and-interface/</guid><description>Methods enhance types with additional behavior.
Methods of the type are called Method Set.
To attach method to a type :
// Syntax // &amp;ldquo;varName Type&amp;rdquo; is called a &amp;ldquo;receiver&amp;rdquo; func (varName Type) funcName() { // Code }
// Example // &amp;ldquo;book&amp;rdquo; is a struct here func (b book) printBook() { fmt.Println(b.title, b.price) }
- A `receiver` is nothing but method&amp;#39;s `input parameters` written `before` a `method name`. - A `method` belongs to a `single type`.</description></item><item><title>Nil values</title><link>https://golang.k5kc.com/2020/08/16/nil-values/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/nil-values/</guid><description/></item><item><title>Pass slice as a function argument</title><link>https://golang.k5kc.com/2020/08/16/pass-slice-as-a-function-argument/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/pass-slice-as-a-function-argument/</guid><description>In Go, the function parameters are passed by value. With respect to use slice as a function argument, that means the function will get the copies of the slice: a pointer which points to the starting address of the underlying array, accompanied by the length and capacity of the slice. Oh boy! Since you know the address of the memory which is used to store the data, you can tweak the slice now.</description></item><item><title>Prepend in Slice</title><link>https://golang.k5kc.com/2020/08/16/prepend/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/prepend/</guid><description>Go has a built-in append function which add elements in the slice:
func append(slice []Type, elems &amp;hellip;Type) []Type
But how if we want to the &amp;ldquo;prepend&amp;rdquo; effect? Maybe we should use copy function. E.g.:
package main import &amp;#34;fmt&amp;#34; func main() { var s []int = []int{1, 2} fmt.Println(s) s1 := make([]int, len(s) + 1) s1[0] = 0 copy(s1[1:], s) s = s1 fmt.Println(s) } The result is like this:
[1 2] [0 1 2] But the above code looks ugly and cumbersome, so an elegant implementation maybe here:</description></item><item><title>Printf and Sprintf formatting</title><link>https://golang.k5kc.com/2020/08/16/printf-sprintf-formatting/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/printf-sprintf-formatting/</guid><description>Following formatting can be used with fmt.Printf as well as fmt.Sprintf:
// String and slice of bytes %s // the uninte­rpreted bytes of the string or slice %q // a double­-quoted string safely escaped with Go syntax %x // base 16, lower-­case, two characters per byte %X // base 16, upper-­case, two characters per byte // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // Boolean %t // the word true or false // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // General %v // The value in a default format.</description></item><item><title>Reallocating underlying array of slice</title><link>https://golang.k5kc.com/2020/08/16/reallocating-underlying-array-of-slice/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/reallocating-underlying-array-of-slice/</guid><description>When appending data into slice, if the underlying array of the slice doesn&amp;rsquo;t have enough space, a new array will be allocated. Then the elements in old array will be copied into this new memory, accompanied with adding new data behind. So when using Go built-in append function, you must always keep the idea that &amp;ldquo;the array may have been changed&amp;rdquo; in mind, and be very careful about it, otherwise, it may bite you!</description></item><item><title>Scopes in Go</title><link>https://golang.k5kc.com/2020/08/16/6.scopes/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/6.scopes/</guid><description>Same name cannot be declared again inside a same scope. There are following types of scopes in Go:
package: Each Go package has it&amp;rsquo;s own scope. For e.g. declared funcs are only visible to the files belonging to same package. file: Imported packages are only visible to the importing file. Each file has to import external packages on it&amp;rsquo;s own. func. block.</description></item><item><title>Slice vs Arrays</title><link>https://golang.k5kc.com/2020/08/16/slice-vs-array/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/slice-vs-array/</guid><description>Performance Slice operations are cheap! Slicing: Creates a new slice header. Assigning a Slice to another Slice or, passing it to a function: Only copies the slice header. Slice header has a fixed size and it doesn't change even if we have got millions of elements. Array can be expensive as compared to Slice. Assigning an array to another array or passing it to a function: Copies all the elements of it.</description></item><item><title>The internals of slice</title><link>https://golang.k5kc.com/2020/08/16/the-internals-of-slice/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/the-internals-of-slice/</guid><description>There are 3 components of slice:
a) Pointer: Points to the start position of slice in the underlying array;
b) length (type is int): the number of the valid elements of the slice;
b) capacity (type is int): the total number of slots of the slice.
Check the following code:
package main import ( &amp;#34;fmt&amp;#34; &amp;#34;unsafe&amp;#34; ) func main() { var s1 []int fmt.Println(unsafe.Sizeof(s1)) } The result is 24 on my 64-bit system (The pointer and int both occupy 8 bytes).</description></item><item><title>Two-dimensional slice</title><link>https://golang.k5kc.com/2020/08/16/two-dimensional-slice/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/two-dimensional-slice/</guid><description>Go supports multiple-dimensional slice, but I only want to introduce two-dimensional slice here. One reason is the two-dimensional slice is usually used in daily life, while multiple-dimensional seems not common. If you often use multiple-dimensional slice, personally I think the code is a little clumsy and not easy to maintain, so maybe you can try to check whether there is a better method; the other reason is the principle behind multiple-dimensional slice is the same with two-dimensional slice, you can also understand it if you know two-dimensional slice well.</description></item><item><title>Type assertion and type switch</title><link>https://golang.k5kc.com/2020/08/16/5.type-assertion-and-type-switch/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/5.type-assertion-and-type-switch/</guid><description>If we have a value and want to convert it to another or a specific type (in case of interface{}), we can use type assertion. A type assertion takes a value and tries to create another version in the specified explicit type.
This is how we can use type assertion:
x.(T) x is the variable whose type must be interface, and T is the type which you want to check. For example:</description></item><item><title>Unused variables</title><link>https://golang.k5kc.com/2020/08/16/9.unused-variables/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/9.unused-variables/</guid><description>Unused variables in blocked scope are not allowed in Go since they cause maintenance nightmares. If we declare a variable in blocked scope then we must use it or else completely remove it from the block. We cannot have unused variables declared in blocked scope dangling in our source codes. Go throws unused variable errors at compile time only. We should avoid using package level variables. Go doesn&amp;rsquo;t throw unused variable errors at compile time for variables declared at package level.</description></item><item><title>Use govendor to implement vendoring</title><link>https://golang.k5kc.com/2020/08/16/use-govendor-to-implement-vendoring/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/use-govendor-to-implement-vendoring/</guid><description>The meaning of vendoring in Go is squeezing a project&amp;rsquo;s all dependencies into its vendor directory. Since Go 1.6, if there is a vendor directory in current package or its parent&amp;rsquo;s directory, the dependency will be searched in vendor directory first. Govendor is such a tool to help you make use of the vendor feature. In the following example, I will demonstrate how to use govendor step by step:
(1) To be more clear, I clean $GOPATH folder first:</description></item><item><title>Variables</title><link>https://golang.k5kc.com/2020/08/16/1.variables-and-inferred-types/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/1.variables-and-inferred-types/</guid><description>In Go, we have to declare a variable before we can use it. This is required and necessary for the compile time safety. Variables are not created at compile time. They are created at run time. The unnamed variables are pointers (like in C). Once we declare a type for a variable, it cannot be changed later. It is static. Declaring with var The var statement declares a list of variables with the type declared last.</description></item><item><title>Zero Values</title><link>https://golang.k5kc.com/2020/08/16/zero-values/</link><pubDate>Sun, 16 Aug 2020 00:10:00 +0530</pubDate><guid>https://golang.k5kc.com/2020/08/16/zero-values/</guid><description>When a variable is declared and it isn&amp;rsquo;t assigned any value at the time of declaration, Go will assign a zero value to it based on it&amp;rsquo;s variable type.
Type of a variable decides what a zero value to it will take initially when declared (and if it isn&amp;rsquo;t assigned any value at the time of declaration).
// Zero Values assigned to variables by Go when they are declared and not assigned any values at the time of declaration.</description></item></channel></rss>