Projects & Modules

TaskCode ExampleDescription
Creating a new go project
mkdir myproject
cd myproject
go mod init myproject

link

https://go.dev/ref/mod#go-mod-init

Download modulesgo mod vendorhttps://go.dev/ref/mod#go-mod-vendor

Cleanup modules

go mod tidy

Ensures that the go.mod file matches the source code in the module.

https://go.dev/ref/mod#go-mod-tidy


Building

TaskCode ExampleDescription
Build

go build  -o mysvc

Build project


Data Types

TypeNotes

bool


string


int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr


byte

alias for uint8

rune

alias for int32
represents a Unicode code point

float32 float64


complex64 complex128



Variables declared without an explicit initial value are given their zero value.


Type Conversion

The expression T(v) converts the value v to the type T.

i := 42
f := float64(i)
u := uint(f)


Constants

const Pi = 3.14


Variables

The var statement declares a list of variables; as in function argument lists, the type is last.

A var statement can be at package or function level. We see both in this example.

A var declaration can include initializers, one per variable.

Inside a function, the := short assignment statement can be used in place of a vardeclaration with implicit type.

package main

import "fmt"

var c, python, java bool
var i, j int = 1, 2

func main() {
	var i int
	x := 10
	fmt.Println(i, c, python, java, x)
}


Arrays

The type [n]T is an array of n values of type T.

The expression

var a [10]int


Functions

  • A function can take zero or more arguments.
  • A function can return any number of results.
  • When two or more consecutive named function parameters share a type, you can omit the type from all but the last.


example:

package main

import "fmt"

func swap(x, y string) (string, string) {
	return y, x
}

func main() {
	a, b := swap("hello", "world")
	fmt.Println(a, b)
}


Defer

A defer statement defers the execution of a function until the surrounding function returns.

The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.

Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order.

package main

import "fmt"

func main() {
	defer fmt.Println("world")

	fmt.Println("hello")
}



Types/Objects

TaskCode ExampleReference
Creating an instance of a struct
type Student struct {
	Name string
	Age  int
}


b := Student{ Name: "Bob", }
p := &Student{ Name: "Bob", } //pointer to Student


var pa *Student   // pa == nil
pa = new(Student) // pa == &Student{"", 0}
pa.Name = "Alice" // pa == &Student{"Alice", 0}
link

Implementing an Interface


In this example, we see that AcousticGuitarist and BaseGuitarist both implement the PlayGuitar function.

package main

import "fmt"

type Guitarist interface {
    // PlayGuitar prints out "Playing Guitar"
    // to the terminal
    PlayGuitar()
}


type BaseGuitarist struct {
    Name string
}

type AcousticGuitarist struct {
    Name string
}

func (b BaseGuitarist) PlayGuitar() {
    fmt.Printf("%s plays the Bass Guitar\n", b.Name)
}

func (b AcousticGuitarist) PlayGuitar() {
    fmt.Printf("%s plays the Acoustic Guitar\n", b.Name)
}

func main() {
    var player BaseGuitarist
    player.Name = "Paul"
    player.PlayGuitar()

    var player2 AcousticGuitarist
    player2.Name = "Ringo"
    player2.PlayGuitar()
}


link

Casting Interface to Concrete


v = i.(T)
v = i.(T)
where i is the interface and T is the concrete type.

It will panic if the underlying type is not T.
To have a safe cast, you use:

v, ok = i.(T)

ex:
var mongoClient = client.(*MongoClient)


Testing

TaskCode ExampleReference

Testing

package rest

import (
	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestGetHealthOK(t *testing.T) {

	req := httptest.NewRequest(http.MethodGet, "/monitor/health", nil)
	rec := httptest.NewRecorder()
	c, _ := gin.CreateTestContext(rec)
	c.Request = req
	getHealth(c)

	//assert.NoError(t, err)
	assert.Equal(t, http.StatusOK, rec.Code)
}


References

  • No labels