Go, is a statically typed, object-oriented, compiled language meant to replace C, and it's used to build high-performance server-side applications. Go was designed by Ken Thompson, Rob Pike, and Robert Greismer at Google, in 2007 and it first appeared on November 10, 2009; 12 years ago, version 1.0 was released in March 2012. Go is compiled to an executable binary and it runs quite fast, faster than your average JavaScript. Go is inspired by languages like C, Pascal, Modula, and Modula-2
It was created to address criticism of other languages, but keep their useful characteristics, which is why it is loved so much, Go combines;
- Static Typing and Runtime Efficiency.
- Readability and usability
- Multiprocessing and Networking.
Go is statically typed but doesn't feel like you're using a statically typed language, this is due to type inference. This gives a Go code a scripting feel and keeps the code concise and clean. Go is the language used to build several tools like
- Docker
- Cockroach DB
Go is designed to be simple and efficient and we will briefly cover the following;
- Hello world program.
- Basic overview of the program and features of a Go program.
- Types
- Strings
- Maths
- Booleans
- Conditionals
- arrays and slices
- Loops
- Functions
- Maps
- Structs
To read more articles like this visit Netcreed
Hello World
package main
import "fmt"
func main() {
fmt.Println("hello world")
}
Let's break down the code, The package
main tells the Go compiler that the package should compile as an executable program instead of a shared library. The main
function in the main package is the entry point of the program, it is where our code will begin execution. We also import the fmt
library which handles formatted input/output. We use the Println
Method to print a message to the standard output or console.
Program Overview
Every Go package will have the following structure,
- It will contain a package declaration.
- Import one or more libraries you need to use.
- main function that will serve as an entry point to our application.
- one or more declared variables.
- one or more functions
Types In Go
Go is a statically typed language and requires that you specify variable types when they are declared. Go is also capable of type inference, the major types in Go are listed below;
- Strings are used to represent character sequence and are enclosed in double quotes.
- Integers are used for numbers, there are different types of integers in Go,
int
,int8
, andint32
amongst others. There is alsouint
which is used to represent unsigned integers. - Floats are used for floating point numbers, e.g 2.3
float32
andfloat64
. - Booleans which are represented by
bool
, store true or false in a single byte. - Struct is used to define more complex data structures by composing one or more primitive types.
- Arrays which are used to store collection of data of similar types.
- Slices which are similar to arrays but they don't require a fixed length.
Let's explore how to explicitly set types and how to allow Go infer types.
package main
import "fmt"
func main() {
// explicit typing
var message string = "hello world"
// type inference
age := 100
fmt.Println(message);
}
Strings
Strings are sequences of Unicode characters enclosed in double quotes. A string is a sequence of immutable bytes, which means once a string is created you cannot change that string.
package main
import "fmt"
func main() {
message := "hello world"
fmt.Println(message);
}
To manipulate strings we can import the strings
library which is built into Go.
package main
import (
"fmt"
"strings"
)
func main() {
message := "hello world"
// convert text to lowercase
fmt.Println(strings.ToLower(message))
// convert text to uppercase
fmt.Println(strings.ToUpper(message))
// separate a string into an array
fmt.Println(strings.Split(message, " "))
}
Math & Numbers
The math library holds utility functions that provide some basic math functionality, allowing us to perform all types of arithmetic calculations.
package main
import (
"fmt"
"math"
)
func main() {
num := 2.40
myNum := 2 * 3
fmt.Println(math.ceil(num))
fmt.Println(math.floor(num))
fmt.Println(math.Sqrt(myNum))
fmt.Println(math.Pi * math.ciel(num))
}
Booleans
Booleans are used to represent truthful or false values and are used in conjunction with conditional statements to enable our code to handle different branching situations.
package main
import "fmt"
func main() {
myAge := 39
mumAge := 58
isBool := myAge == mumAg
isAdult := myAge > 18
fmt.Println(isBool)
fmt.Println(isAdult)
}
Conditionals
These are statements that allow branching and decision-making in our code based on the results of an expression which is a boolean. We have the normal if
Statement and the switch
statements to handle conditionals.
package main
import "fmt"
func main() {
num := 16
if num > 18 {
fmt.Println("you're an adult")
} else {
fmt.Println("you're a child")
}
}
Notice the lack of parenthesis enclosing the condition, this is a feature of Go's syntax. This makes our code cleaner and more readable let's check out the switch statement. Switch statements are used to compose multiple if statements in a readable format.
Switch
package main
import "fmt"
func main() {
option := "Y"
Switch option {
case "Y":
fmt.Println("continue")
break;
case "N":
fmt.Println("stop")
break;
default:
fmt.Println("invalid option")
break;
}
}
Arrays & Slices
Arrays are fixed-length sequences used to store the collection of the same data type. Arrays in go are similar to arrays in other languages, however, they have a slightly different syntax.
package main
import "fmt"
func main() {
nums := [3]int{1, 5, 7, 0};
fmt.Println(len(nums))
names := [2]string{"sam", "john"}
fmt.Println(names[0])
names[1] = "Bob";
fmt.Println(names)
}
Slices are similar to arrays, the key difference between a slice and an array is the lack of a fixed length in the slice, when we declare a slice there's no need to explicitly define the length of the slice, allowing us to get a scripting-like feel. This behavior is found in languages like JavaScript and python.
package main
import "fmt"
func main() {
nums := []int{1, 5, 7, 0};
fmt.Println(len(nums))
names := []string{"Fred", "bob"}
fmt.Println(names)
}
Arrays and slices begin at a zero index as is standard with most languages. Most of the time you'd be using slices due to the flexibility they provide. We can use the append
function which is provided globally to add an item or another array/slice to the one we already do. Another method, delete
which is also provided globally can be used to remove an item from a list.
package main
import "fmt"
func main() {
nums := []int{1, 5, 7, 0};
// add an item
newNums = append(nums, 9)
fmt.Println(len(newNums))
// add a list item
names := []string{"Fred", "bob"}
nNames = append(names, {"sam", "pam"})
fmt.Println(names)
delete(names, 0)
fmt.Println(len(nNames))
}
Loops
Loops are fundamental to most programming languages and they are implemented in quite an interesting manner in Go. There is only a for loop in Go, so don't expect to see while
or do
as you'd find in most programming language.
package main
import "fmt"
func main() {
for i := 0; i < 5; i ++ {
fmt.Println(i)
}
}
Notice again the lack of parenthesis, we can shorten the loop expression by taking the variable declaration to a line above the for loop, then increment our counter inside the loop.
package main
import "fmt"
func main() {
i := 0
for i; i < 5; {
fmt.Println(i)
i++;
}
}
We can also loop over arrays and slices, there are two ways of doing this. We can use the standard method by utilizing the built range
method or we use the len
method, let's look at the latter first.
package main
import "fmt"
func main() {
nums := [3]int{1, 5, 7, 0};
for i := 0; i < len(nums); {
fmt.Println(nums[i])
i++;
}
}
The range
Method is syntactically better than the len
as we will see below;
package main
import "fmt"
func main() {
nums := [3]int{1, 5, 7, 0};
for index, value := range nums {
fmt.Println(index, value)
}
}
Functions
Functions are at the heart of all programming languages, functions in go are declared using the func
keyword. Each parameter passed into the function should be of a specified type and if the function returns a value, ensure to specify it too, let's create a function.
package main
import "fmt"
func getArea(r float64) float64 {
return r * 2;
}
func main() {
nums := []int{1, 5, 7, 0};
area := getArea(nums[1])
fmt.Println(area)
}
Go supports functional programming, there are higher-order functions, functions can be assigned to variables, passed as arguments to other functions, and we can also return functions from functions. Go also allows us to return multiple values from a function
package main
import "fmt"
func getArea(r float64) float64 {
return r * 2;
}
func getNums(n uint, p uint) (uint, uint, uint) {
return n * p, n + p, p * 2
}
func isOdd(num float64) float64 {
isOdd := num ℅ 2 == 0
if isOdd {
return true
}
return false
}
func main() {
num := 3
num := isOdd(getArea(num))
fmt.Println(num)
fmt.Println(getNums(4, 3))
}
Maps
Maps are complex data structures used to store key-value pairs, a map allows you to associate a key that can be of any basic data type with a value that can be of another type. It's more like a dictionary in python.
package main
import "fmt"
func main() {
var ages map[string]int
ages["sam"] = 40
ages["phill"] = 30
}
You can also loop through a map because it is a collection, we can use the range function with a for loop to achieve this.
package main
import "fmt"
func main() {
var ages map[string]int
ages["sam"] = 40
ages["phill"] = 30
for key, value := range ages {
fmt.Println(key, value)
}
}
Structs
A struct is a type that is used to describe more complex form of data that closely resembles real-world data.
package main
import "fmt"
type Person struct {
name string
age int
hobbies [2]string
}
func main() {
lily := Person{"Lily", 3, {"singing", "dancing"}}
fmt.Println(lily)
}
To read more articles like this visit Netcreed
Top comments (2)
Thank you for your article. I've never dealed with programming, would like to try as evening hobby.
Glad you found it useful, you could check my other topics on coding.