Skip to content

AnonnaGH/Golang_practice

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Golang_practice

Go is a popular programming language.
Go is used to create computer programs.

Go Introduction

What is Go?

Go is a cross-platform, open source programming language
Go can be used to create high-performance applications
Go is a fast, statically typed, compiled language that feels like a dynamically typed, interpreted language
Go was developed at Google by Robert Griesemer, Rob Pike, and Ken Thompson in 2007
Go's syntax is similar to C++

What is Go Used For?

Web development (server-side)
Developing network-based programs
Developing cross-platform enterprise applications

Cloud-native development

Go Compared to Python and C++

image

Notes:

Compilation time refers to translating the code into an executable program

Concurrency is performing multiple things out-of-order, or at the same time, without affecting the final outcome

Statically typed means that the variable types are known at compile time

Go Compact Code

You can write more compact code, like shown below (this is not recommended because it makes the code more difficult to read):
image

Go Syntax

A Go file consists of the following parts:

Package declaration

Import packages

Functions

Statements and expressions

Look at the following code, to understand it better:

Example

package main
import ("fmt")

func main() {
fmt.Println("Hello World!")
}

Example explained

Line 1: In Go, every program is part of a package. We define this using the package keyword. In this example, the program belongs to the main package.

Line 2: import ("fmt") lets us import files included in the fmt package.

Line 3: A blank line. Go ignores white space. Having white spaces in code makes it more readable.

Line 4: func main() {} is a function. Any code inside its curly brackets {} will be executed.

Line 5: fmt.Println() is a function made available from the fmt package. It is used to output/print text. In our example it will output "Hello World!".

Note:

In Go, any executable code belongs to the main package.

Go Comments

A comment is a text that is ignored upon execution.

Comments can be used to explain the code, and to make it more readable.

Comments can also be used to prevent code execution when testing an alternative code.

Go supports single-line or multi-line comments.

Go Single-line Comments

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by the compiler (will not be executed).

Go Multi-line Comments

Multi-line comments start with /* and ends with */.

Comment to Prevent Code Execution

You can also use comments to prevent the code from being executed.

The commented code can be saved for later reference and troubleshooting.

Go Variable Types

In Go, there are different types of variables, for example:

int- stores integers (whole numbers), such as 123 or -123

float32- stores floating point numbers, with decimals, such as 19.99 or -19.99

string - stores text, such as "Hello World". String values are surrounded by double quotes

bool- stores values with two states: true or false

Go Variable Types

In Go, there are different types of variables, for example:

int- stores integers (whole numbers), such as 123 or -123
float32- stores floating point numbers, with decimals, such as 19.99 or -19.99
string - stores text, such as "Hello World". String values are surrounded by double quotes
bool- stores values with two states: true or false

Declaring (Creating) Variables

In Go, there are two ways to declare a variable:

1. With the var keyword:

Use the var keyword, followed by variable name and type:
image

Note: You always have to specify either type or value (or both).

2. With the := sign:

Use the := sign, followed by the variable value:
image

Note: In this case, the type of the variable is inferred from the value (means that the compiler decides the type of the variable, based on the value).

Note: It is not possible to declare a variable using :=, without assigning a value to it.

Variable Declaration With Initial Value

If the value of a variable is known from the start, you can declare the variable and assign a value to it on one line: image

Variable Declaration Without Initial Value

In Go, all variables are initialized. So, if you declare a variable without an initial value, its value will be set to the default value of its type:
image

Example explained

In this example there are 3 variables:

a
b
c

These variables are declared but they have not been assigned initial values.

By running the code, we can see that they already have the default values of their respective types:

a is ""
b is 0
c is false

Value Assignment After Declaration

It is possible to assign a value to a variable after it is declared. This is helpful for cases the value is not initially known.

image

Note: It is not possible to declare a variable using ":=" without assigning a value to it.

Difference Between var and :=

There are some small differences between the var var :=

image

Example

This example shows declaring variables outside of a function, with the var keyword:
image

image

Go Multiple Variable Declaration

In Go, it is possible to declare multiple variables in the same line.

package main
import ("fmt")

func main() {
  var a, b, c, d int = 1, 3, 5, 7

  fmt.Println(a)
  fmt.Println(b)
  fmt.Println(c)
  fmt.Println(d)
}

Note: If you use the type keyword, it is only possible to declare one type of variable per line.

If the type keyword is not specified, you can declare different types of variables in the same line:

package main
import ("fmt")

func main() {
  var a, b = 6, "Hello"
  c, d := 7, "World!"

  fmt.Println(a)
  fmt.Println(b)
  fmt.Println(c)
  fmt.Println(d)
}

Go Variable Declaration in a Block

Multiple variable declarations can also be grouped together into a block for greater readability:

package main
import ("fmt")

func main() {
   var (
     a int
     b int = 1
     c string = "hello"
   )

  fmt.Println(a)
  fmt.Println(b)
  fmt.Println(c)
}

Go Variable Naming Rules

A variable can have a short name (like x and y) or a more descriptive name (age, price, carname, etc.).

Go variable naming rules:

A variable name must start with a letter or an underscore character (_)
A variable name cannot start with a digit
A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
There is no limit on the length of the variable name
A variable name cannot contain spaces
The variable name cannot be any Go keywords

Multi-Word Variable Names

Variable names with more than one word can be difficult to read.

There are several techniques you can use to make them more readable:

Camel Case

Each word, except the first, starts with a capital letter:

myVariableName = "John"

Pascal Case

Each word starts with a capital letter:

MyVariableName = "John"

Snake Case

Each word is separated by an underscore character:

my_variable_name = "John"

Go Constants

If a variable should have a fixed value that cannot be changed, you can use the const keyword.

The const keyword declares the variable as "constant", which means that it is unchangeable and read-only.
image

Note: The value of a constant must be assigned when you declare it.

Declaring a Constant

Here is an example of declaring a constant in Go:

package main
import ("fmt")

const PI = 3.14

func main() {
  fmt.Println(PI)
}

Constant Rules

Constant names follow the same naming rules as variables
Constant names are usually written in uppercase letters (for easy identification and differentiation from variables)
Constants can be declared both inside and outside of a function

Constant Types

There are two types of constants:

Typed constants

Untyped constants

Typed Constants

Typed constants are declared with a defined type:

package main
import ("fmt")

const A int = 1

func main() {
  fmt.Println(A)
}

Untyped Constants

Untyped constants are declared without a type:

package main
import ("fmt")

const A = 1

func main() {
  fmt.Println(A)
}

Note: In this case, the type of the constant is inferred from the value (means the compiler decides the type of the constant, based on the value).

Constants: Unchangeable and Read-only

When a constant is declared, it is not possible to change the value later:

image

Multiple Constants Declaration

Multiple constants can be grouped together into a block for readability:

package main
import ("fmt")

const (
  A int = 1
  B = 3.14
  C = "Hi!"
)

func main() {
  fmt.Println(A)
  fmt.Println(B)
  fmt.Println(C)
}

Go Output Functions

Go has three functions to output text:
image

@ The Print() Function The Print() function prints its arguments with their default format.

Print the values of i and j:

image

If we want to print the arguments in new lines, we need to use \n.

package main
import ("fmt")

func main() {
  var i,j string = "Hello","World"

  fmt.Print(i, "\n")
  fmt.Print(j, "\n")
}

image

It is also possible to only use one Print() for printing multiple variables.

package main
import ("fmt")

func main() {
  var i,j string = "Hello","World"

  fmt.Print(i, "\n",j)
}

image

If we want to add a space between string arguments, we need to use " ":

we want to add a space between string arguments, we need to use " ":

package main
import ("fmt")

func main() {
  var i,j string = "Hello","World"

  fmt.Print(i, " ", j)
}

image

Print() inserts a space between the arguments if neither are strings:

image

The Println() Function

The Println() function is similar to Print() with the difference that a whitespace is added between the arguments, and a newline is added at the end:

package main
import ("fmt")

func main() {
  var i,j string = "Hello","World"

  fmt.Println(i,j)
}

image

The Printf() Function

The Printf() function first formats its argument based on the given formatting verb and then prints them.

Here we will use two formatting verbs:

%v is used to print the value of the arguments

%T is used to print the type of the arguments

package main
import ("fmt")

func main() {
  var i string = "Hello"
  var j int = 15

  fmt.Printf("i has value: %v and type: %T\n", i, i)
  fmt.Printf("j has value: %v and type: %T", j, j)
}

image

Go Formatting Verbs

Formatting Verbs for Printf()

Go offers several formatting verbs that can be used with the Printf() function.

General Formatting Verbs

The following verbs can be used with all data types:
image

package main
import ("fmt")

func main() {
  var i = 15.5
  var txt = "Hello World!"

  fmt.Printf("%v\n", i)
  fmt.Printf("%#v\n", i)
  fmt.Printf("%v%%\n", i)
  fmt.Printf("%T\n", i)

  fmt.Printf("%v\n", txt)
  fmt.Printf("%#v\n", txt)
  fmt.Printf("%T\n", txt)
}

image

Integer Formatting Verbs

The following verbs can be used with the integer data type:

image

package main
import ("fmt")

func main() {
  var i = 15
 
  fmt.Printf("%b\n", i)
  fmt.Printf("%d\n", i)
  fmt.Printf("%+d\n", i)
  fmt.Printf("%o\n", i)
  fmt.Printf("%O\n", i)
  fmt.Printf("%x\n", i)
  fmt.Printf("%X\n", i)
  fmt.Printf("%#x\n", i)
  fmt.Printf("%4d\n", i)
  fmt.Printf("%-4d\n", i)
  fmt.Printf("%04d\n", i)
}

image

String Formatting Verbs

The following verbs can be used with the string data type:

image

`` golang package main import ("fmt")

func main() { var txt = "Hello"

fmt.Printf("%s\n", txt) fmt.Printf("%q\n", txt) fmt.Printf("%8s\n", txt) fmt.Printf("%-8s\n", txt) fmt.Printf("%x\n", txt) fmt.Printf("% x\n", txt) }

![image](https://user-images.githubusercontent.com/44522472/157442364-ee1be2cc-b3c1-431d-aa34-730dd4eaf56e.png)

# Boolean Formatting Verbs
### The following verb can be used with the boolean data type:
![image](https://user-images.githubusercontent.com/44522472/157442435-d0dcf9e4-3a01-456b-908b-298ef100eda5.png)

``` golang 
package main
import ("fmt")

func main() {
  var i = true
  var j = false

  fmt.Printf("%t\n", i)
  fmt.Printf("%t\n", j)
}

image

Float Formatting Verbs

The following verbs can be used with the float data type:

image

Go Data Types

Data type is an important concept in programming. Data type specifies the size and type of variable values.

Go is statically typed, meaning that once a variable type is defined, it can only store data of that type.

Go has three basic data types:

bool: represents a boolean value and is either true or false

Numeric: represents integer types, floating point values, and complex types

string: represents a string value

package main
import ("fmt")

func main() {
  var a bool = true     // Boolean
  var b int = 5         // Integer
  var c float32 = 3.14  // Floating point number
  var d string = "Hi!"  // String

  fmt.Println("Boolean: ", a)
  fmt.Println("Integer: ", b)
  fmt.Println("Float:   ", c)
  fmt.Println("String:  ", d)
}

Boolean Data Type

A boolean data type is declared with the bool keyword and can only take the values true or false.

The default value of a boolean data type is false.

package main
import ("fmt")

func main() {
  var b1 bool = true // typed declaration with initial value
  var b2 = true // untyped declaration with initial value
  var b3 bool // typed declaration without initial value
  b4 := true // untyped declaration with initial value

  fmt.Println(b1) // Returns true
  fmt.Println(b2) // Returns true
  fmt.Println(b3) // Returns false
  fmt.Println(b4) // Returns true
}

Note: Boolean values are mostly used for conditional testing

Go Integer Data Types

Integer data types are used to store a whole number without decimals, like 35, -50, or 1345000.

The integer data type has two categories:

Signed integers: can store both positive and negative values
Unsigned integers: - can only store non-negative values

Signed Integers

Signed integers, declared with one of the int keywords, can store both positive and negative values:

Go has five keywords/types of signed integers:

image

Unsigned Integers

Unsigned integers, declared with one of the uint keywords, can only store non-negative values:

package main
import ("fmt")

func main() {
  var x uint = 500
  var y uint = 4500
  fmt.Printf("Type: %T, value: %v", x, x)
  fmt.Printf("Type: %T, value: %v", y, y)
}

Go Arrays

Arrays are used to store multiple values of the same type in a single variable, instead of declaring separate variables for each value.

Declare an Array

In Go, there are two ways to declare an array:

1. With the var keyword:

image

2. With the := sign:

image

Note: The length specifies the number of elements to store in the array. In Go, arrays have a fixed length. The length of the array is either defined by a number or is inferred (means that the compiler decides the length of the array, based on the number of values).

Array Examples

This example declares two arrays (arr1 and arr2) with defined lengths:

package main
import ("fmt")

func main() {
  var arr1 = [3]int{1,2,3}
  arr2 := [5]int{4,5,6,7,8}

  fmt.Println(arr1)
  fmt.Println(arr2)
}

image

package main
import ("fmt")

func main() {
  var arr1 = [...]int{1,2,3}
  arr2 := [...]int{4,5,6,7,8}

  fmt.Println(arr1)
  fmt.Println(arr2)
}

image

package main
import ("fmt")

func main() {
  var cars = [4]string{"Volvo", "BMW", "Ford", "Mazda"}
  fmt.Print(cars)
}

image

Access Elements of an Array

You can access a specific array element by referring to the index number.

In Go, array indexes start at 0. That means that [0] is the first element, [1] is the second element, etc.

This example shows how to access the first and third elements in the prices array:

package main
import ("fmt")

func main() {
  prices := [3]int{10,20,30}

  fmt.Println(prices[0])
  fmt.Println(prices[2])
}

image

Change Elements of an Array

You can also change the value of a specific array element by referring to the index number.

package main
import ("fmt")

func main() {
  prices := [3]int{10,20,30}

  prices[2] = 50
  fmt.Println(prices)
}

image

Change Elements of an Array

You can also change the value of a specific array element by referring to the index number.

package main
import ("fmt")

func main() {
  prices := [3]int{10,20,30}

  prices[2] = 50
  fmt.Println(prices)
}

#Array Initialization

If an array or one of its elements has not been initialized in the code, it is assigned the default value of its type.

Tip: The default value for int is 0, and the default value for string is "".

package main
import ("fmt")

func main() {
  arr1 := [5]int{} //not initialized
  arr2 := [5]int{1,2} //partially initialized
  arr3 := [5]int{1,2,3,4,5} //fully initialized

  fmt.Println(arr1)
  fmt.Println(arr2)
  fmt.Println(arr3)
}

Initialize Only Specific Elements

It is possible to initialize only specific elements in an array.

package main
import ("fmt")

func main() {
  arr1 := [5]int{1:10,2:40}

  fmt.Println(arr1)
}

Example Explained

The array above has 5 elements.

1:10 means: assign 10 to array index 1 (second element).
2:40 means: assign 40 to array index 2 (third element).

Find the Length of an Array

The len() function is used to find the length of an array:

package main
import ("fmt")

func main() {
  arr1 := [4]string{"Volvo", "BMW", "Ford", "Mazda"}
  arr2 := [...]int{1,2,3,4,5,6}

  fmt.Println(len(arr1))
  fmt.Println(len(arr2))
}

image

Go Slices

Slices are similar to arrays, but are more powerful and flexible.

Like arrays, slices are also used to store multiple values of the same type in a single variable.

However, unlike arrays, the length of a slice can grow and shrink as you see fit.

In Go, there are several ways to create a slice:

Using the []datatype{values} format
Create a slice from an array
Using the make() function

Create a Slice With []datatype{values}

image

A common way of declaring a slice is like this:
image

The code above declares an empty slice of 0 length and 0 capacity.

To initialize the slice during declaration, use this:
image The code above declares a slice of integers of length 3 and also the capacity of 3.

In Go, there are two functions that can be used to return the length and capacity of a slice:

len() function - returns the length of the slice (the number of elements in the slice) cap() function - returns the capacity of the slice (the number of elements the slice can grow or shrink to)

package main
import ("fmt")

func main() {
  myslice1 := []int{}
  fmt.Println(len(myslice1))
  fmt.Println(cap(myslice1))
  fmt.Println(myslice1)

  myslice2 := []string{"Go", "Slices", "Are", "Powerful"}
  fmt.Println(len(myslice2))
  fmt.Println(cap(myslice2))
  fmt.Println(myslice2)
}

image

Create a Slice From an Array

You can create a slice by slicing an array:

var myarray = [length]datatype{values} // An array
myslice := myarray[start:end] // A slice made from the array

This example shows how to create a slice from an array:

package main
import ("fmt")

func main() {
  arr1 := [6]int{10, 11, 12, 13, 14,15}
  myslice := arr1[2:4]

  fmt.Printf("myslice = %v\n", myslice)
  fmt.Printf("length = %d\n", len(myslice))
  fmt.Printf("capacity = %d\n", cap(myslice))
}

image

In the example above myslice is a slice with length 2. It is made from arr1 which is an array with length 6.

The slice starts from the second element of the array which has value 12. The slice can grow to the end of the array. This means that the capacity of the slice is 4.

If myslice started from element 0, the slice capacity would be 6.

Create a Slice With The make() Function

The make() function can also be used to create a slice.

slice_name := make([]type, length, capacity)

Note: If the capacity parameter is not defined, it will be equal to length.

package main
import ("fmt")

func main() {
  myslice1 := make([]int, 5, 10)
  fmt.Printf("myslice1 = %v\n", myslice1)
  fmt.Printf("length = %d\n", len(myslice1))
  fmt.Printf("capacity = %d\n", cap(myslice1))

  // with omitted capacity
  myslice2 := make([]int, 5)
  fmt.Printf("myslice2 = %v\n", myslice2)
  fmt.Printf("length = %d\n", len(myslice2))
  fmt.Printf("capacity = %d\n", cap(myslice2))
}

image

Go Access, Change, Append and Copy Slices

Access Elements of a Slice
You can access a specific slice element by referring to the index number.

In Go, indexes start at 0. That means that [0] is the first element, [1] is the second element, etc.

package main
import ("fmt")

func main() {
  prices := []int{10,20,30}

  fmt.Println(prices[0])
  fmt.Println(prices[2])
}

Output

image

Change Elements of a Slice

You can also change a specific slice element by referring to the index number.

package main
import ("fmt")

func main() {
  prices := []int{10,20,30}
  prices[2] = 50
  fmt.Println(prices[0])
  fmt.Println(prices[2])
}

output

image

Append Elements To a Slice

You can append elements to the end of a slice using the append()function:

Syntax

image

package main

import (
	"fmt"
)

func main() {

	s := []int{1, 2, 3, 4, 5, 6}
	fmt.Printf("s = %v\n", s)
	fmt.Printf("length = %d\n", len(s))
	fmt.Printf("capacity = %d\n", cap(s))

	s = append(s, 20, 21, 22, 23, 24, 25)
	fmt.Printf("s = %v\n", s)
	fmt.Printf("length = %d\n", len(s))
	fmt.Printf("capacity =%d\n", cap(s))

	s = append(s, 30, 36)
	fmt.Printf("s = %v\n", s)
	fmt.Printf("length = %d\n", len(s))
	fmt.Printf("capacity =%d\n", cap(s))

}

output

image

Go Operators

Conditional statements are used to perform different actions based on different conditions.

Go Conditions
A condition can be either true or false.

Go supports the usual comparison operators from mathematics:

Less than <
Less than or equal <=
Greater than >
Greater than or equal >=
Equal to ==
Not equal to !=
Additionally, Go supports the usual logical operators:

Logical AND &&
Logical OR ||
Logical NOT !
You can use these operators or their combinations to create conditions for different decisions.

image

package main
import ("fmt")

func main() {
  x := 10
  y := 5
  fmt.Println(x > y)
}

image

package main
import ("fmt")

func main() {
  x := 10
  y := 5
  fmt.Println(x != y)
}

image

package main
import ("fmt")

func main() {
  x := 10
  y := 5
  z := 2
  fmt.Println((x > y) && (y > z))
}

image

package main
import ("fmt")

func main() {
  x := 10
  y := 5
  z := false
  fmt.Println((x == y) || z)
}

image

Go has the following conditional statements:

Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed

Go if statement

Use the if statement to specify a block of Go code to be executed if a condition is true.

Syntax

image

package main
import ("fmt")

func main() {
  if 20 > 18 {
    fmt.Println("20 is greater than 18")
  }
}

image

package main
import ("fmt")

func main() {
  x := 20
  y := 18
  if x>y {
    fmt.Println("x is greater than y")
  }
}

image

Example explained

In the example above we use two variables, x and y, to test whether x is greater than y (using the > operator). As x is 20, and y is 18, and we know that 20 is
greater than 18, we print to the screen that "x is greater than y".

Go if else Statement

The else Statement
Use the else statement to specify a block of code to be executed if the condition is false.

Syntax

image

Using The if else Statement

In this example, time (20) is greater than 18, so the if condition is false. Because of this, we move on to the else condition and print to the screen "Good evening". If the time was less than 18, the program would print "Good day":

package main
import ("fmt")

func main() {
  time := 20
  if (time < 18) {
    fmt.Println("Good day.")
  } else {
    fmt.Println("Good evening.")
  }
}

image

In this example, the temperature is 14 so the condition for if is false so the code line inside the else statement is executed:

package main
import ("fmt")

func main() {
  temperature := 14
  if (temperature > 15) {
    fmt.Println("It is warm out there")
  } else {
    fmt.Println("It is cold out there")
  }
}

The brackets in the else statement should be like } else {:

image

Go else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax

image

Using The else if Statement

package main
import ("fmt")

func main() {
  time := 22
  if time < 10 {
    fmt.Println("Good morning.")
  } else if time < 20 {
    fmt.Println("Good day.")
  } else {
    fmt.Println("Good evening.")
  }
}

image

Example explained

In the example above, time (22) is greater than 10, so the first condition is false. The next condition, in the else if statement, is also false, so we move on to
else condition since condition1 and condition2 are both false - and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."
`` golang package main import ("fmt")

func main() { a := 14 b := 14 if a < b { fmt.Println("a is less than b.") } else if a > b { fmt.Println("a is more than b.") } else { fmt.Println("a and b are equal.") } }

![image](https://user-images.githubusercontent.com/44522472/159615073-27ecab29-842d-4180-b106-9ea47bf70cc8.png)

## If conditions1 and condition2 are both correct, only the code for condition1 are executed:
``` golang
package main
import ("fmt")

func main() {
  x := 30
  if x >= 10 {
    fmt.Println("x is larger than or equal to 10.")
  } else if x > 20
    fmt.Println("x is larger than 20.")
  } else {
    fmt.Println("x is less than 10.")
  }
}

image

Go Nested if Statement

You can have if statements inside if statements, this is called a nested if.

Syntax

image

package main
import ("fmt")

func main() {
  num := 20
  if num >= 10 {
    fmt.Println("Num is more than 10.")
    if num > 15 {
      fmt.Println("Num is also more than 15.")
     }
  } else {
    fmt.Println("Num is less than 10.")
  }
}

image

Go switch Statement

Use the switch statement to select one of many code blocks to be executed.

The switch statement in Go is similar to the ones in C, C++, Java, JavaScript, and PHP. The difference is that it only runs the matched case so it does not need a
break statement.

Single-Case switch Syntax

image

This is how it works:

The expression is evaluated once
The value of the switch expression is compared with the values of each case
If there is a match, the associated block of code is executed
The default keyword is optional. It specifies some code to run if there is no case match

Single-Case switch Example

The example below uses a weekday number to calculate the weekday name:

package main
import ("fmt")

func main() {
  day := 4

  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")
  }
}

image

The default Keyword

The default keyword specifies some code to run if there is no case match:

package main
import ("fmt")

func main() {
  day := 8

  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("Not a weekday")
  }
}

image

All the case values should have the same type as the switch expression. Otherwise, the compiler will raise an error:

image

The Multi-case switch Statement

It is possible to have multiple values for each case in the switch statement:

Syntax

image

Multi-case switch Example

The example below uses the weekday number to return different text:

package main
import ("fmt")

func main() {
   day := 5

   switch day {
   case 1,3,5:
    fmt.Println("Odd weekday")
   case 2,4:
     fmt.Println("Even weekday")
   case 6,7:
    fmt.Println("Weekend")
  default:
    fmt.Println("Invalid day of day number")
  }
}

Go For Loops

The for loop loops through a block of code a specified number of times.

The for loop is the only loop available in Go.

Go for Loop

Loops are handy if you want to run the same code over and over again, each time with a different value.

Each execution of a loop is called an iteration.

The for loop can take up to three statements:

Syntax

image

statement1 Initializes the loop counter value.

statement2 Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.

statement3 Increases the loop counter value.

Note: These statements don't need to be present as loops arguments. However, they need to be present in the code in some form.

for Loop Examples

package main

func main() {
	for i := 0; i < 5; i++ {
		println(i)
	}

}

image

Example 1 explained

i:=0; - Initialize the loop counter (i), and set the start value to 0
i < 5; - Continue the loop as long as i is less than 5
i++ - Increase the loop counter value by 1 for each iteration

package main
import ("fmt")

func main() {
  for i:=0; i <= 100; i+=10 {
    fmt.Println(i)
  }
}

image

Example 2 explained

i:=0; - Initialize the loop counter (i), and set the start value to 0
i <= 100; - Continue the loop as long as i is less than or equal to 100
i+=10 - Increase the loop counter value by 10 for each iteration

The continue Statement

The continue statement is used to skip one or more iterations in the loop. It then continues with the next iteration in the loop.

Example

package main
import ("fmt")

func main() {
  for i:=0; i < 5; i++ {
    if i == 3 {
      continue
    }
    fmt.Println(i)
  }
}

image

The break Statement

The break statement is used to break/terminate the loop execution.
This example breaks out of the loop when i is equal to 3:

package main
import ("fmt")

func main() {
  for i:=0; i < 5; i++ {
    if i == 3 {
      break
    }
   fmt.Println(i)
  }
}

Nested Loops

It is possible to place a loop inside another loop.

Here, the "inner loop" will be executed one time for each iteration of the "outer loop":

package main
import ("fmt")

func main() {
  adj := [2]string{"big", "tasty"}
  fruits := [3]string{"apple", "orange", "banana"}
  for i:=0; i < len(adj); i++ {
    for j:=0; j < len(fruits); j++ {
      fmt.Println(adj[i],fruits[j])
    }
  }
}

image

The Range Keyword

The range keyword is used to more easily iterate over an array, slice or map. It returns both the index and the value.

The range keyword is used like this:

Syntax

image

Example

This example uses range to iterate over an array and print both the indexes and the values at each (idx stores the index, val stores the value):

package main
import ("fmt")

func main() {
  fruits := [3]string{"apple", "orange", "banana"}
  for idx, val := range fruits {
     fmt.Printf("%v\t%v\n", idx, val)
  }
}

image

To only show the value or the index, you can omit the other output using an underscore (_).

Here, we want to omit the indexes (idx stores the index, val stores the value):

package main
import ("fmt")

func main() {
  fruits := [3]string{"apple", "orange", "banana"}
  for _, val := range fruits {
     fmt.Printf("%v\n", val)
  }
}

image

Here, we want to omit the values (idx stores the index, val stores the value):

package main
import ("fmt")

func main() {
  fruits := [3]string{"apple", "orange", "banana"}

  for idx, _ := range fruits {
     fmt.Printf("%v\n", idx)
  }

image

Go Functions

A function is a block of statements that can be used repeatedly in a program.

A function will not execute automatically when a page loads.

A function will be executed by a call to the function.

Create a Function

To create (often referred to as declare) a function, do the following:

Use the func keyword.

Specify a name for the function, followed by parentheses ().
Finally, add code that defines what the function should do, inside curly braces {}.
image

Call a Function

Functions are not executed immediately. They are "saved for later use", and will be executed when they are called.

In the example below, we create a function named "myMessage()". The opening curly brace ( { ) indicates the beginning of the function code, and the closing curly brace ( } ) indicates the end of the function. The function outputs "I just got executed!". To call the function, just write its name followed by two parentheses ():

Example

package main
import ("fmt")

func myMessage() {
 fmt.Println("I just got executed!")
}

func main() {
 myMessage() // call the function
}

Result:

image

A function can be called multiple times.

package main
import ("fmt")

func FunctionName() {
  fmt.Println("I just got executed!")
}

func main() {
  myMessage()
  myMessage()
  myMessage()
}

Result:

image

Go Function Parameters and Arguments

Parameters and Arguments

Information can be passed to functions as a parameter. Parameters act as variables inside the function.

Parameters and their types are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma:

Syntax

image

Function With Parameter Example

The following example has a function with one parameter (fname) of type string. When the familyName() function is called, we also pass along a name (e.g. Liam), and the name is used inside the function, which outputs several different first names, but an equal last name:

Example

package main
import ("fmt")

func familyName(fname string) {
  fmt.Println("Hello", fname, "Refsnes")
}

func main() {
  familyName("Liam")
  familyName("Jenny")
  familyName("Anja")
}

result

image

Multiple Parameters

Inside the function, you can add as many parameters as you want:

Example

package main
import ("fmt")

func familyName(fname string, age int) {
  fmt.Println("Hello", age, "year old", fname, "Refsnes")
}

func main() {
  familyName("Liam", 3)
  familyName("Jenny", 14)
  familyName("Anja", 30)
}

Result:

image

Note: When you are working with multiple parameters, the function call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.

Go Function Returns

Return Values

If you want the function to return a value, you need to define the data type of the return value (such as int, string, etc), and also use the return keyword inside the function:

Syntax

image

Function Return Example

Here, myFunction() receives two integers (x and y) and returns their addition (x + y) as integer (int):

package main
import ("fmt")

func myFunction(x int, y int) int {
  return x + y
}

func main() {
  fmt.Println(myFunction(1, 2))
}

Result:

image

Named Return Values

In Go, you can name the return values of a function.

Example

Here, we name the return value as result (of type int), and return the value with a naked return (means that we use the return statement without specifying the variable name):

package main
import ("fmt")

func myFunction(x int, y int) (result int) {
  result = x + y
  return
}

func main() {
  fmt.Println(myFunction(1, 2))
}

Result:

image

The example above can also be written like this. Here, the return statement specifies the variable name:

package main
import ("fmt")

func myFunction(x int, y int) (result int) {
  result = x + y
  return result
}

func main() {
  fmt.Println(myFunction(1, 2))
}

Store the Return Value in a Variable

You can also store the return value in a variable, like this:

Example

Here, we store the return value in a variable called total:

package main
import ("fmt")

func myFunction(x int, y int) (result int) {
  result = x + y
  return
}

func main() {
  total := myFunction(1, 2)
  fmt.Println(total)
}

Multiple Return Values

Go functions can also return multiple values.

Example

Here, myFunction() returns one integer (result) and one string (txt1):

package main
import ("fmt")

func myFunction(x int, y string) (result int, txt1 string) {
  result = x + x
  txt1 = y + " World!"
  return
}

func main() {
  fmt.Println(myFunction(5, "Hello"))
}

Result:

image

Example

Here, we store the two return values into two variables (a and b):

package main
import ("fmt")

func myFunction(x int, y string) (result int, txt1 string) {
  result = x + x
  txt1 = y + " World!"
  return
}

func main() {
  a, b := myFunction(5, "Hello")
  fmt.Println(a, b)
}

Result:

image

If we (for some reason) do not want to use some of the returned values, we can add an underscore (_), to omit this value.

Example

Here, we want to omit the first returned value (result - which is stored in variable a):

package main
import ("fmt")

func myFunction(x int, y string) (result int, txt1 string) {
  result = x + x
  txt1 = y + " World!"
  return
}

func main() {
   _, b := myFunction(5, "Hello")
  fmt.Println(b)
}

Result:

image

Example

Here, we want to omit the second returned value (txt1 - which is stored in variable b):

package main
import ("fmt")

func myFunction(x int, y string) (result int, txt1 string) {
  result = x + x
  txt1 = y + " World!"
  return
}

func main() {
   a, _ := myFunction(5, "Hello")
  fmt.Println(a)
}

Result:

image

Go Recursion Functions

Go

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Languages