
- Go - Home
- Go - Overview
- Go - Environment Setup
- Go - Program Structure
- Go - Basic Syntax
- Go - Data Types
- Go - Variables
- Go - Constants
- Go - Identifiers
- Go - Keywords
- Go - Operators
- Go - Arithmetic Operators
- Go - Assignment Operators
- Go - Relational Operators
- Go - Logical Operators
- Go - Bitwise Operators
- Go - Miscellaneous Operators
- Go - Operators Precedence
- Go Decision Making
- Go - Decision Making
- Go - If Statement
- Go - If Else Statement
- Go - Nested If Statements
- Go - Switch Statement
- Go - Select Statement
- Go Control Flow Statements
- Go - For Loop
- Go - Nested for Loops
- Go - Break Statement
- Go - Continue Statement
- Go - Goto Statement
- Go Functions
- Go - Functions
- Go - Call by Value
- Go - Call by Reference
- Go - Functions as Values
- Go - Function Closure
- Go - Function Method
- Go - Anonymous function
- Go Strings
- Go - Strings
- Go - String Length
- Go - String Concatenation
- Go - Compare Strings
- Go - Split String
- Go - Substring Extraction
- Go - String Replacement
- Go - String Interpolation
- Go - Parse Date Strings
- Go Arrays
- Go - Arrays
- Go - Multidimensional Arrays
- Go - Multidimensional Arrays
- Go - Passing Arrays to Functions
- Go - Pointers
- Go - Pointers
- Go - Array of pointers
- Go - Pointer to pointer
- Go - Passing pointers to functions
- Go Advanced Control Structures
- Go - Scope Rules
- Go - Dereferencing Pointer
- Go - Structures
- Go - Slice
- Go - Slice of Slices
- Go - Range
- Go - Maps
- Go - Recursion
- Go - Type Casting
- Go - Interfaces
- Go - Type Assertion
- Go - Error Handling
- Go - Concurrency
- Go - Regular Expression
- Go - Inheritance
- Go - Packages
- Go - Templates
- Go - Reflection
- Go - Generics
- Go File Handling
- Go - Read File By Word
- Go - Read File By Line
- Go - Read CSV Files
- Go - Delete File
- Go - Rename & Move File
- Go - Truncate a File
- Go - File Read-Write Mode W/O Truncation
- Go Miscellaneous
- Go - defer Keyword
- Go - Fmt Package
- Go - Zero Value
- Go - Import
Golang Cheatsheet
This is the Golang cheatsheet, which provides everything from basic to advanced concepts to help you grow as a programmer. By learning this cheatsheet, students and developers can prepare for interviews. Go through the cheatsheet to learn the concepts of Golang programming.
Table of Content
- Basics Overview of Golang
- Arithmetic Operators
- Relational Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Miscellaneous Operators
1. Basics Overview of Golang
In the basics of Golang, we will learn about the fundamental topics:
i. Syntax
Golang syntax is very simple to use. Here is an example to display "Welcome to Tutorialspoint" in Golang.
package main import "fmt" func main() { fmt.Println("Welcome to Tutorialspoint") }
ii. Data Types
The data types are used to declare the variables or functions of different types. Following is the table that helps you to get the understanding of various data types in golang −
Integer | Floating-point | Complex number | Strings | Boolean |
---|---|---|---|---|
int, int8, int16, int32, int64 | float32, float64 | complex64, complex128 | string | bool |
package main import "fmt" func main() { var m int = 100 var n float64 = 99.5 var x bool = true var y string = "Tutorialspoint" fmt.Println(m) fmt.Println(n) fmt.Println(x) fmt.Println(y) }
iii. Variables
Variables are used to store the data values. The basic syntax of a variable in golang −
var variable_name type = value
Note: The symbol ":=" is used to declare the short variable declaration.
package main import "fmt" func main() { var id int = 30 name := "John" fmt.Println("ID:", name) fmt.Println("Address:", id) }
iv. Constants
Constants of Golang, use the keyword consts. This cannot be change after being set.
package main import "fmt" func main() { const PI float64 = 3.14159 fmt.Println("Value of PI:", PI) }
v. Comments
Comments in Golang are written in two ways − single-line comment (//) and multi-line comments (/* ... */).
package main import "fmt" // Single line comment func main() { /* fmt.Println("Welcome") fmt.Println("to") fmt.Println("Tutorialspoint") */ }
2. Control Structures in Golang
The control structure is a block of code that determines the flow of execution in a program based on conditions and loops.
i. If Statements
The if statement specifies the block of code if a condition is true.
package main import "fmt" func main() { // taking a local variable var n int = 800 if n < 5000 { fmt.Printf("n is less than 5000\n") } fmt.Printf("Value of n is : %d\n", n) }
ii. If-Else Statement
The if-else statement specifies the code block if the condition is false.
package main import "fmt" func main() { num := 0 // Check whether it is positive, negative, or zero if num > 0 { fmt.Println("The given number is positive.") } else if num < 0 { fmt.Println("The given number is negative.") } else { fmt.Println("The given number is zero.") } }
iii. Nested-If Statement
The nested-if statement is defined using an if statement inside another if statement.
package main import "fmt" func main() { number := 8 // nested-if statement if number > 0 { fmt.Println("The number is positive.") if number%2 == 0 { fmt.Println("The number is even.") } else { fmt.Println("The number is odd.") } } else { fmt.Println("The number is zero or negative.") } }
iv. Switch Statements
The switch statement is used to execute one block of code when the case matches.
package main import "fmt" func main() { day := 4 // Switch statement to check the day of the week switch day { case 1: fmt.Println("Monday") case 2: fmt.Println("Tuesday") case 3: fmt.Println("Wednesday") case 4: fmt.Println("Thursday") case 5: fmt.Println("Friday") case 6: fmt.Println("Saturday") case 7: fmt.Println("Sunday") default: fmt.Println("Invalid day") } }
v. For Loops
A for loop is defined by the repetition of a control structure.
package main import "fmt" func main() { // Using a for loop to print numbers 1 through 5 for i := 1; i <= 5; i++ { fmt.Println(i) } }
vi. Range
In Golang, range is a keyword that is used for the iteration of various data structures such as arrays, slices, strings, maps, and channels.
package main import "fmt" func main() { num := []int{10, 20, 30, 40, 50} // iterate over the slice for idx, val := range num { fmt.Println("Index:", idx, "Value:", val) } }
vii. Slice
A slice of Go defines the variable-length sequence that stores the elements of the same type.
package main import "fmt" func main() { arr := []int{1, 2, 3, 4, 5, 6, 7, 8} slice := arr[3:5] fmt.Println("Array: ", arr) fmt.Println("Slice: ", slice) }
viii. Maps
Maps are used to store data in key:value pairs.
package main import ("fmt") func main() { var X = map[string]string{"Stree 2 ": " 15 AUG 2024", "Pushpa 2 ": " 5 DEC 2024", "Mufasa ": " 20 DEC 2024"} Y := map[string]int{"A": 1, "B": 2, "C": 3, "D": 4} fmt.Printf("I.\t%v\n", X) fmt.Printf("II.\t%v\n", Y) }
3. Pointer in Golang
In Golang, a pointer refers to a specified memory location of the value.
i. Pointer
This is the basic program of pointer in Golang.
package main import "fmt" func main() { var n int = 58 // declare a pointer in int var ptr *int // store the address of n to ptr ptr = &n fmt.Println("Value of num:", n) fmt.Println("Address of num:", &n) fmt.Println("Pointer (address) stored in ptr:", ptr) fmt.Println("Value at ptr (dereferencing):", *ptr) }
Golang Operators
The operators of Golang allows user to perform different types of operation which is listed below −
- Arithmetic Operators: These operators are used to perform basic mathematical operations such as addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).
- Relational Operators: Relational operators compare two values and return a boolean result (true or false). Common operators include <, , >, >=, ==, and !=.
- Logical Operators: These operators are used to perform logical operations. They include AND (&&), OR (||), and NOT (!).
- Bitwise Operators: Bitwise operators perform operations on binary representations of numbers. They include AND (&), OR (|), XOR (^), left shift (<<), and right shift (>>).
- Assignment Operators: These operators assign values to variables. In Golang, the common assignment operator is =. Additionally, shorthand operators like +=, -=, and *= are also available.
- Miscellaneous Operators: These include operators like the increment (++) and decrement (--) operators.
5. Control Flow Statement in Golang
The control flow statement determines the order in which instructions are executed in a program.
i. break statement
The break statement stops executing the loops.
package main import "fmt" func main() { fmt.Println("Illustration of break statement:") for i := 1; i <= 4; i++ { if i == 2 { break // Exit the loop when i is 2 } fmt.Println(i) } }
ii. continue statement
The continue statement skips the current iteration in the loop.
package main import "fmt" func main() { fmt.Println("Illustration of continue statement:") for i := 1; i <= 6; i++ { if i == 3 { continue // Skip the iteration when i is 3 } fmt.Println(i) } }
iii. goto statement
The goto statement jumps to a specified label in code.
package main import "fmt" func main() { /* local variable definition */ var a int = 10 /* do loop execution */ LOOP: for a < 20 { if a == 15 { /* skip the iteration */ a = a + 1 goto LOOP } fmt.Printf("value of a: %d\n", a) a++ } }
6. Golang Functions
The Golang function is reusable code that can be used for specific tasks.
i. Function Declaration
To declare a function in golang, use func keyword −
func FunctionName() { // code to be executed }
ii. Return Values
A function that can return any number of values is known as return values.
package main import "fmt" // calculate the sum of two numbers func sum(a, b int) int { return a + b } func main() { // call the sum() result := sum(3, 4) fmt.Println("Sum:", result) }
iii. Variadic Functions
A variadic function in Golang allows the user to pass n numbers as arguments. The ellipsis is denoted by three dots (...).
package main import "fmt" // calculate the sum using variadic function func sum(nums ...int) int { total := 0 for _, n := range nums { total += n } return total } func main() { fmt.Println("Sum of 1, 2, 3, 7, 1:", sum(1, 2, 3, 7, 1)) fmt.Println("Sum of 6, 5:", sum(6, 5)) }
iv. Anonymous Functions
This type of function doesn't have a name.
package main import "fmt" func main() { // Anonymous function func() { fmt.Println("Welcome to Tutorialspoint!") }() }
7. Structure and Interfaces in Golang
Structure defines the collection of members of different data types. This stores all the data into a single variable. This type of function doesn't have a name.
i. type and struct
To declare a structure, use the keyword struct and type −
type struct_name struct { member_1 string member_2 int member_3 string member_4 int }
ii. Interfaces
Here is the basics of interfaces in golang language −
type InterfaceName interface { Method_1() returnType Method_2() returnType }
iii. Type Assertion
Type assertion is used to check whether an interface holds a specific type and extract the value of that type.
package main import "fmt" func main() { var i interface{} = "Tutorialspoint" t := i.(string) fmt.Println(t) t, p := i.(string) fmt.Println(t, p) f, p := i.(float64) fmt.Println(f, p) f = i.(float64) // panic fmt.Println(f) }
8. Golang Concurrency
Concurrency in Golang refers to the ability of handling multiple tasks. This can be achieved using goroutines, channels, and the select statement.
i. Goroutines
Goroutines in Golang are independent functions that run concurrently. It means handling multiple tasks within a single program.
package main import "fmt" func display(str string) { for i := 0; i < 4; i++ { fmt.Println(str) } } func main() { // Runs concurrently go display("Hello, Goroutine!") display("Hello, Main!") }
ii. Channels
A channel is a medium that allows one goroutine to communicate with another goroutine.
package main import "fmt" func main() { // Create the channel using var var channel_1 chan int fmt.Println("Value of the channel: ", channel_1) fmt.Printf("Type of the channel_1: %T ", channel_1) // Create the channel using make() function channel_2 := make(chan int) fmt.Println("\nValue of the channel1: ", channel_2) fmt.Printf("Type of the channel_2: %T ", channel_2) }
iii. Select Statement
In Golang, the select statement is used to handle multiple communications, like sending and receiving values.
select { case value := <- channel1: // Executes when channel1 has data to receive case channel2 <- value: // Executes when channel2 is ready to accept data default: // Executes when none of the channels are ready }
9. Error Handling in Golang
Error handling defines the process of detecting the error during the program execution.
i. Error Types
In Golang, errors are represented by the error. The following is a list of errors based on different scenarios −
- Built-in error type: This is represented by errors.new function from the error package to build a simple error value.
- Formatted error: This is represented by fmt.Errorf function that allows users to create errors with formatted messages.
- custom error: This is implemented using the error() method.
// Built-in error errors.New("division by zero is not allowed") // Formatted Error fmt.Errorf("...write something...", filename) // Custom error type error interface { error() string }
ii. Panic and Recover
In Golang, a panic is defined as a runtime error that stops the program execution unless it is recovered using recover. We can say this is used for programming bugs.
a. This is the basic example of panic.
package main import "fmt" func main() { fmt.Println("The program starts...") // Trigger a panic panic("Something went wrong!") fmt.Println("This will not be displayed") }
b. This is the example of the recover() function that is used within the inside defer statement that catches and handles panics.
package main import "fmt" func safeDivide(x, y int) { defer func() { if z := recover(); z != nil { fmt.Println("Recovered from panic:", z) } }() if y == 0 { panic("division by zero") } fmt.Println("Result:", x/y) } func main() { fmt.Println("Start program") safeDivide(100, 0) fmt.Println("End program") }
10. Golang Packages
In Golang, packages are collections of relatable source files that organise, modularise, and be reusable.
i. Importing Packages
Golang is organised by packages, which allows users to modularise and reuse the code.
package main import ( // Import fmt package "fmt" // Import math package "math" ) func main() { fmt.Println("Square root of 100 is:", math.Sqrt(100)) }
ii. Creating Packages
To create custom packages in Golang, follow the below steps −
- Step 1: Create a folder for the package. For example − gopackage
- Step 2: Write the code for the package. For example − mention the path "path/to/package".
package main import ( "fmt" // replace the actual path to your package "path/to/mypackage" ) func main() { sum := mypackage.Add(2, 3) product := mypackage.Multiply(10, 5) fmt.Println("Sum of two numbers:", sum) // 5 fmt.Println("Product of two numbers:", product) // 50 }
11. File Handling in Golang
File handling in Golang allows users to interact with data that is stored on the disk.
i. Reading Files
To read the file, use the os and io/ioutil packages.
package main import ( "fmt" "io/ioutil" "log" ) func main() { // Reading the file data, err := ioutil.ReadFile("file.txt") if err != nil { log.Fatal(err) } // Display the content fmt.Println(string(data)) }
ii. Writing Files
While writing into a file, use the os.WriteFile(). Below is the basic example −
package main import ( "log" "os" ) func main() { // write something to it data := []byte("Hello!\nWelcome to Tutorialspoint.") // Write the content to a file er := os.WriteFile("example_file.txt", data, 8649) if er != nil { log.Fatalf("Failed to write to file: %v", er) } log.Println("The written files is printed successfully!") }
12. Testing in Golang
Golang testing package tests whether the program is being run or not.
i. Writing Tests
The testing package of Golang is used for writing tests. Thus, this verifies the correctness of the code.
package main import "testing" // function to test func add(a, b int) int { return a + b } // Test function func TestAdd(t *testing.T) { result := add(2, 3) if result != 5 { t.Errorf("Add(2, 3) = %d; want 5", result) } }
Note: The TestAdd function is used for testing. Suppose the result of add(2, 3) is not 5; then it reports the error using t.Errorf().
ii. Running Tests
To run the tests, use the following command −
go test
13. Common Libraries in Golang
Golang libraries are pre-written code modules that process everyday tasks.
i. Standard Library Overview
Some of the common libraries that are mostly used in Golang programming −
Golang Libraries | Description |
---|---|
import "fmt" | This provides formatting strings, reading input, and printing output. |
import "os" | This provides a function to interact with the operating system. |
import "json" | This provides functions for encoding and decoding JSON data. |
import "error" | This provides a function to create and handle errors. |
import "regexp" | This provides a function for compiling regular expressions. |
import "io" | This provides basic input-output operations like reading and writing. |
import "math" | This provides mathematical functions like trigonometric, exponential, and logarithmic operations. |
import "strings" | This provides a string for manipulation and processing. |