Although Golang does not support inheritance, we can achieve similar results through the usage of type definitions and type embedding.
Let's start with a simple object: we need to store contacts data:
and birthday will be composed by:
As we have seen in a previous post (Arrays vs Slices), in Golang, a slice is just a header pointing to a backing array.
In this post, we will discuss slices again and we will focus on some pitfalls regarding the append
function.
Let's start with a very simple example declaring 2 slices: one co...
Working with GO, one is tempted to think that arrays and slices are the same things other than array having an immutable size. That's not true and some quirks should be known. Take the following function for example (for readability no checks are done on slice bounds):
type NamesStruct struct {...
Optimizing struct size can improve both memory usage and application performance. Let's look at the following example:
package main
import (
"fmt"
"unsafe"
)
type Contact struct {
enabled bool
name string
surname string
isSpam bool
age int
}
func main() {...
Checking for a nil
value is very common in GO programs so it is important to know the difference between checking nil
on a given type and checking nil
on an interface{}
object.
Let's start with an example:
package main
import "fmt"
func GiveMeANil(value *string) {
if value == nil {...
There are 3 ways people use to close a response body and I call them The Good, The Bad and The Ugly way.
It is not rare to find code like this:
resp,err := http.Get("https://mysite.com")
defer resp.Body.Close()
if err != nil {
// handle error
return e...
Suppose you have a slice declared as:
names := []string{"Manyanda", "Abhishek", "Pawel", "Eoin", "Jameel", "Vincent", "Jason", "Massimo"}
and a printSlice
function that prints the first count
element of the passed in slice implemented like this:
func printSlice(slice []*string, count int)...
Go is not an object-oriented language, however, it allows you to implement both Methods
and Functions
.
A Method
is simply a Function
with a receiver.
Look at the code below:
package main
import (
"fmt"
)
type Contact struct {
name string
surna...