This repository contains the go-funtamentals to understand the basic contructs of go-lang.
- Modern & clean
- System language
- Wide range of usecases
- Strongly typed
- Compiled
- Concurrency support
- Cross-platform support
Installing go lang is very easy, just go to go install page and follow instructions.
-
package structure:
module |--- package |--- source-files
-
Create directory to start using as
go modulewhich will contain all the srouce code related to that module. -
e.g.
mkdir go-fundamentalsthis is my go module for developement. -
To init the above directory to be work as go module you will need to initialize with module initialization command.
-
Use command
go mod init {optional/package/name}this will create go.mod file with module name and go versoin used to create the module. -
Create new directory to start using as
go packagewhich will logically group your source code files. -
e.g.
mkdir hello-worldthis is my go package which will have code related to hello-world. -
Inside the
hello-worldfolder you can have source files as part of hello-world package. -
e.g. you can refer to hello-world/hello.go file is source code file containing the source code related to hello-world package.
Go provide different ways to bundle, run application. Depends upon the requirement you can use the any command to either run build or install your application.
go run {filename}will allow you to run the go source file directly.- it will build the application at
temp locationand thenrunit andcleanthe file
- it will build the application at
go build <optional|package>will create theexecutable filedepends on the which enviorment you are building the source code.- by default takes the current package directory name, you can aleaways specify the name of file
go install <optional|packagename>willbuildand place the executable file in your$HOMEdirectory.
- Creating your first
Hello Worldgo code, first follow the packaging instruction above. - Now you have package with
hello.gofile created, to write you first code refer to hello.go file. - To import any existing package use
import {package-name}e.g.import fmtso we can use the fuctions present in the package.
- Declaring variables
- Any variable declared outside the function at package level must do it with
varkeyword. No non declartion statements at package level are allowed. - Varibale names should
- start with
letter - not be
Go Keyword - not have any
spaces - not have any
special character
- start with
- Good practices:
- use meaningful names
- keep short
- can use
camelCase
- Any variable declared outside the function at package level must do it with
Keep first character of variable
lowercase, else makingcapitalletterwill make that variable visible outside the package it defined.
- Example:
var ( name string course string module, clip = 2, 1 )
- Scope of above declared vars is global in package.
- Variable declaration inside the function
var description stringthis is if you dont have any default assignment to set variabledescription := "this is go fundamental course"you can set the value directly to initialize.- operator
:=is short assignment operator used to assign the value to vars.
You can declare varibale at
packagelevel and not use is allowed. but if you declare variable inside thefunctionyou have to use the variable.
- Values and Pointers
- Go passes arguments
by valuesandnot by references - When you pass the var directly to any function its pass by value
len(title)- To get memory address, you have to use
&sign likefmt.Println(&title)will give something like0xc000088250
- To get memory address, you have to use
- Go provides
pointersto point to other variables- Pointer variable e.g.
var ptr *string = &titlehere*make the variableptra pointer var pointing to memory address oftitlevar *ptrwill yeid value is hold by the variable pointed to whichvar ptris pointing.
- Pointer variable e.g.
- Pass by Reference
- To pass the value as reference to function you need to use the
&variableand in function you need to use the pointer variabel to reference the var likevariable *type - then you can use
*variable = {new valuue}to update the variable passed by reference which will actually update the value in original variable.
- To pass the value as reference to function you need to use the
- Constants in go
- Contants can be created using keyword
constin go - for example
const speedOfLight = 186000 - Once create you can not change the value of constant.
- Contants can be created using keyword
- Enviorment Variables
- You can access the enviorment vars using package
osin go - which will allow you to read env vars.
- You can access the enviorment vars using package
- Go passes arguments
- why do you functions? code reusability!
input->Function->output- Syntax of functions in Go
func functionName(params, type) returnType { <code> }
- above code snippet says,
funcis keyword to declare function followed bynameof fuction. which takesparameterswith itstypethen followed by thereturn typeof function. - Example:
func updateCourse(course string) course string { course = "new course" return course }
- You can refer to convert.go full running source file.
- Funtion with Varying number of parameters
- To create functoin which accepts varying params
func varyingfuncName(param ...type) returnType { <code> }
- Important part is
paramName ...typeis says it accepts the varying number of parameters. you can refer varying-params-fuction.go
- To create functoin which accepts varying params
-
the
ifsyntax evaluates the condition and executes code based on it.- conditional if else in go
if userAge > 18 { <code> }
- conditional
elsewith if
if userAge > 18 { <code> } else { <code> }
- if else with nesting of
if-elseconditions
if userAge > 18 { <code> } else if userAge > 15 { <code> } else { <code> }
- you can also declare the vars in if scope which only avaulable to scope of if else
if userAge, requiredAge := 15, 18; userAge > requiredAge { <code> } else { <code> }
- You can refere to if-example.go to running source code.
-
Switch-case statements in go
- Syntax of
switchstatement.
switch <simple-statment>; <expression> { case <value>: <code> case <value>: <code> default: <code> }
- Go will not execute any statment after matching the case, so
only matchedcase will be executed and if not match it will execute thedefaultone. - Go will have default
breakfor each case statement.- to override behaviour go provides
fallthroughkeyword. - which only applies to case statement its added, which will execute next case statememt only.
- to override behaviour go provides
- You can refer to runnning example of switch-example.go.
- Multiple conditional match in same
casestatement- go provides the way to match the multiple conditionals in same case so you can group behaviour and reduce multiple case statements.
- example: switch-multi-case.go
- Syntax of
-
If with Error handling
- if is most common way to handle
errorin go erroris defined type is go lang.
_, err := os.Open("filename") if err != nil { <code_to_handle_error> }
- You can refer to if-with-errors.go for running example
- if is most common way to handle
- GO has only one loop keyword
forwhich has many way to configure and use as required. - Syntax for loop
for <expression> { <code> }
- here if
expressionistruethat means it will loop until the expression evaluates totrue
- here if
- Infinite
forloopfor { <code> }
- here if we dont specify any expression in for it will loop infinite times
- For loop with
boolean expression- you can use
for {expression_evaluates_to|true|false}to continue/break loop - example can be found at for-loop.go
- You can also write the traditional for loop.
for i:=0; i<10; i++{ <code> }
- Example to run for-loop.go
- you can use
- For Loop with
range expression- You can iterate over the range of items using for loop
for index, item := range rangeVariable { <code> }
- Execute the code for range loop range-for-loop.go
- Break and Continue statements in loop
breakis used in loop to stop the execution of at given statement.continueis used in loop to go back and continue to execute the loop statement.- Example for brak and continue for-break-continue.go
- for
listsin go, all the data types stored in list must be ofsame type - For
list of stringall the data should bestringtype, similarly fornumbersit should brinttype data - Arrays : are like
lists- they have
fix size
- they have
- Slices : are like
arrays- but they are
resizable - they are built top of the
array- So basically no actual data is stored inside the slice, it is actually the
pointerspointing to data stored inside the array - as they are pointers, dont store the data, its cheaper.
- Initialization of empty slice
- So basically no actual data is stored inside the slice, it is actually the
varName := make([]<type>, <length>, <capacity>)
- You can have slice of slices which creates futher smaller pointers of slice
someSlice := []int{1, 2, 3, 4, 5, 6, 7} smallSlice := someSlice[2:7]
- here we have to specify the
[start_index:end_index]to create the slice, whereend_indexisexcludedfrom the result - You can refer the more executable arrays-slices
- but they are
this is very much similar concept of pythons list slicing. you can read more here!
- How Slices are Dyamic (resizable)?
- When the size of
sliceis completly filled, as it uses underlying data storagearray, it will double the size ofarrayand store the next element pointing to next position - You with
sliceyou dont worry about the lenght of array that you need, you can use as resizable array data structure however in case ofarrayyou have to specify and create the size and have manually upgrade lenght do manipulations - Resizable better understanding execute resizable.go.
- When the size of
Mapiskey-valuetype of data structure same as maps, hashTable in other languages.- It stores data in
key -> valueformat. - initialization of map
- syntax
map[<key-type>]<value-type>* `<key-type>` must be **comaprable** data type, like it should work with `== and !=`
* `key entry` must be **unique**.
someMapVar := make(map[string]int)* Here we have create empty map which will hold `string` keys and `int` values.
* Execute [maps-basics.go](maps-in-go/maps-basics.go) for more examples.
* Go maps Object will default return the data with `key ordered` way. like data is sorted based on `keys`
* Retriving data from map using `for` loop will return data **randomly**.
* Execute code [map-iteration.go](maps-in-go/map-iteration.go) to understand this.
- add, update, delete and access value from the map
- Adding new entry to map
- Syntax
mapVar[<newKey>] = <newValue>
- Syntax
- Update entry in map
- Syntax
mapVar[<existingKey>] = <newValue>, if the key dose not exisits inmapit will create new entry, else it will update the value.
- Syntax
- Delete the entry in map
- Syntax
delete(mapVar, <KeyToDelete>)
- Syntax
- Access any value in map
- Syntax
fmt.Println(mapVar[<mapKey>])
- Syntax
- Adding new entry to map
- Execute the map-iteration.go to understand wokring
- Map are
reference typesthey will be passed by reference tofunction, so modifies actual data- so its cheap to work with as its only pointers are passed
- they are not
thread safe
structis way of defining the custom data types in go.- For a basic
personwe can create struct like
type person struct {
name string
age int
address string
}- Object Oriented in GO
- GO does not have
objecttype - Also it dose not have
classkeyword - No
inhearitancesupport
- GO does not have
- Execute code structs-basics.go to understand more.
- You can access the
structfields using.withvarperson.nameorperson.age
- To update the structs fileds data
- you can use
person.age = <new_age>
- you can use
Feel Free to update the documentation and add more relavent contents. Thanks in advance. π€