Go covers

Cheat Sheet

In this Go tutorial, we covered,

Topic Description Syntax
Basic types Numeric, string, bool
Variables Declare and assign values to variables var variable_name type var variable_name type = value var variable_name1, variable_name2 = value1, value2 variable_name := value
Constants Variables whose value cannot be changed once assigned const variable = value
For Loop Execute statements in a loop. for initialisation_expression; evaluation_expression; iteration_expression{ // one or more statement }
If else It is a conditional statement if condition{ // statements_1 }else{ // statements_2 }
switch Conditional statement with multiple cases switch expression { case value_1: statements_1 case value_2: statements_2 case value_n: statements_n default: statements_default }
Array Fixed size named sequence of elements of same type arrayname := [size] type {value_0,value_1,…,value_size-1}
Slice Portion or segment of an array var slice_name [] type = array_name[start:end]
Functions Block of statements which performs a specific task func function_name(parameter_1 type, parameter_n type) return_type { //statements }
Packages Are used to organise the code. Increases code readability and reusability import package_nam
Defer Defers the execution of a function till the containing function finishes execution defer function_name(parameter_list)
Pointers Stores the memory address of another variable. var variable_name *type
Structure User defined datatype which itself contains one more element of the same or different type type structname struct { variable_1 variable_1_type variable_2 variable_2_type variable_n variable_n_type }
Methods A method is a function with a receiver argument func (variable variabletype) methodName(parameter_list) { }
Goroutine A function which can run concurrently with other functions. go function_name(parameter_list)
Channel Way for functions to communicate with each other. A medium to which one routine places data and is accessed by another routine. Declare: ch := make(chan int) Send data to channel: channel_variable <- variable_name Receive from channel: variable_name := <- channel_variable
Select Switch statement which works on channels. The case statements will be a channel operation. When any of the channel is ready with data, then the statement associated with that case is executed select { case x := <-chan1: fmt.Println(x) case y := <-chan2: fmt.Println(y) }
Mutex Mutex is used when you don’t want to allow a resource to be accessed by multiple subroutines at the same time. Mutex has 2 methods – Lock and Unlock mutex.Lock() //statements mutex.Unlock().
Read files Reads the data and returns a byte sequence. Data, err := ioutil.ReadFile(filename)
Write file Writes data to a file l, err := f.WriteString(text_to_write)

Leave a Reply