Variable Declaration
# Declaring variables
name = "John"
age = 30
is_active = True
Lists
# Creating a list
numbers = [1, 2, 3, 4, 5]
# Appending to a list
numbers.append(6)
# Accessing list elements
first_number = numbers[0] # 1
Dictionaries
# Creating a dictionary
person = {"name": "John", "age": 30}
# Accessing dictionary values
name = person["name"]
# Adding new key-value pairs
person["city"] = "New York"
Loops
# For loop
for i in range(5):
print(i)
# While loop
count = 0
while count < 5:
print(count)
count += 1
Conditionals
# If, elif, else
if age < 20:
print("Teenager")
elif age < 60:
print("Adult")
else:
print("Senior")
Functions
# Defining a function
def greet(name):
return "Hello " + name
# Calling a function
greeting = greet("John")
print(greeting)
File Handling
# Writing to a file
with open('example.txt', 'w') as file:
file.write('Hello, World!')
# Reading from a file
with open('example.txt', 'r') as file:
content = file.read()
print(content)
Exception Handling
# Try, except block
try:
result = 10 / 0
except ZeroDivisionError:
print("Divided by zero!")
Modules
# Importing a module
import math
# Using a function from the math module
result = math.sqrt(16) # 4.0
Variable
NAME="John"
echo $NAME
echo "$NAME"
echo "${NAME}
Condition
if [[ -z "$string" ]]; then
echo "String is empty"
elif [[ -n "$string" ]]; then
echo "String is not empty"
fi
Chain command
Chain if the first command succeds
apt update -y && apt upgrade -y
Chain if the first command fails
apt update -y || sudo apt update -y
Pipe
ls -l | grep "config"
Disk Space
df -h
Search
find . -name "*.txt"
Output
ls > files.txt
Strings
str := "Hello"
Multiline string
str := `Multiline
string`
Numbers
Typical types
num := 3 // int
num := 3. // float64
num := 3 + 4i // complex128
num := byte('a') // byte (alias for uint8)
Other Types
var u uint = 7 // uint (unsigned)
var p float32 = 22.7 // 32-bit float
Arrays
// var numbers [5]int
numbers := [...]int{0, 0, 0, 0, 0}
Pointers
func main () {
b := *getPointer()
fmt.Println("Value is", b)
func getPointer () (myPointer *int) {
a := 234
return &a
a := new(int)
*a = 234
Pointers point to a memory location of a variable. Go is fully garbage-collected.
Type Conversion
i := 2
f := float64(i)
u := uint(i)
Slice
slice := []int{2, 3, 4}
slice := []byte("Hello")
Condition
if day == "sunday" || day == "saturday" {
rest()
} else if day == "monday" && isTired() {
groan()
} else {
work()
}
if _, err := doThing(); err != nil {
fmt.Println("Uh oh")
Switch
switch day {
case "sunday":
// cases don't "fall through" by default!
fallthrough
case "saturday":
rest()
default:
work()
}
Loop
for count := 0; count <= 10; count++ {
fmt.Println("My counter is at", count)
}
entry := []string{"Jack","John","Jones"}
for i, val := range entry {
fmt.Printf("At position %d, the character %s is present\n", i, val)
n := 0
x := 42
for n != x {
n := guess()
}
Hello World
A sample go program is show here.
package main
import "fmt"
func main() {
message := greetMe("world")
fmt.Println(message)
}
func greetMe(name string) string {
return "Hello, " + name + "!"
}
Run the program as below:
$ go run hello.go
Variables
Normal Declaration:
var msg string
msg = "Hello"
Shortcut:
msg := "Hello"
Constants
const Phi = 1.618
Condition
if day == "sunday" || day == "saturday" {
rest()
} else if day == "monday" && isTired() {
groan()
} else {
work()
}
if _, err := doThing(); err != nil {
fmt.Println("Uh oh")