Table of contents
- What is Go?
- What is Go Used For?
- Installing Go
- Pre-requisite
- Creating our first Go program
- Comments in Go
- Types of comments
- Variables in Go
- Declaring (Creating) Variables
- With the var keyword:
- With the := Sign:
- Difference Between var and:=
- Go Multiple Variable Declaration
- Go Variable Naming Rules
- Go Constants
- Declaring a Constant
- Go Ouput
- The Print() Function
- The Printf() Function
- Datatypes in Go
- Arrays in Go
- Arrays with inferred lengths
- Access Elements of an Array
- Change Elements of an Array
- Find the Length of an Array
- Slices in Go
- Functions in Go
- Tutorial: Create a Go module
- Calling your code from another module
- Reference
What is Go?
The Go programming language is an open-source project to make programmers more productive.
Go is expressive, concise, clean, and efficient.
Its concurrency mechanisms make it easy to write programs that get the most out of multicore and networked machines, while its novel type system enables flexible and modular program construction.
Go compiles quickly to machine code yet has the convenience of garbage collection and the power of run-time reflection.
It's a fast, statically typed, compiled language that feels like a dynamically typed, interpreted language.
What is Go Used For?
Web development (server-side)
Developing network-based programs
Developing cross-platform enterprise applications
Cloud-native development
Installing Go
Instructions for downloading and installing Go
Pre-requisite
A text editor, like VS Code, to write Go code
A compiler, like GCC, translates the Go code into a language that the computer will understand
Creating our first Go program
Here's the code for the "Hello World!" program
package main
import ("fmt")
func main() {
fmt.Println("Hello World!")
}
Let's go deeper into the syntaxes
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 themain
package.Line 2:
import ("fmt")
lets us import files included in thefmt
package.Line 3: A blank line. Go ignore white space. Having white spaces in the 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 thefmt
package. It is used to output/print text. In our example, it will output "Hello World!".
Comments in Go
A comment is a programmer-readable explanation or annotation in the source code of a computer program that is generally ignored by compilers and interpreters.
They are added to make the source code easier for humans to understand.
Types of comments
Single Line Comments:
// This is a comment package main import ("fmt") func main() { // This is a comment fmt.Println("Hello World!") }
Double Line Comments
package main
import ("fmt")
func main() {
/* The code below will print Hello World
to the screen, and it is amazing */
fmt.Println("Hello World!")
}
Variables in Go
there are different types of variables, for example:
int
- stores integers (whole numbers), such as 123 or -123float32
- stores floating point numbers, with decimals, such as 19.99 or -19.99string
- stores text, such as "Hello World". String values are surrounded by double quotesbool
- stores values with two states: true or false
Declaring (Creating) Variables
With the
var
keyword:var variablename type = value
With the
:=
Sign:
variablename := value
In the above case, the compiler decides the type of the variable, based on the value.
Difference Between var and:=
var | := |
Can be used inside and outside of functions | Can only be used inside functions |
Variable declaration and value assignment can be done separately | Variable declaration and value assignment cannot be done separately (must be done in the same line) |
Go Multiple Variable Declaration
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)
}
Go Variable Naming Rules
Here are some of the rules to name a variable properly in Go.
Go Constants
If a variable should have a fixed value that cannot be changed, you can use the const
keyword.
const CONSTNAME type = value
Declaring a Constant
const pi = 3.14
Go Ouput
We use different types of functions to print something in Go. Here are some of them:
The Print() Function
package main
import ("fmt")
func main() {
var i,j string = "Hello","World"
fmt.Print(i)
fmt.Print(j)
}
HelloWorld
The Printf() Function
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)
}
i has value: Hello and type: string
j has value: 15 and type: int
Datatypes in Go
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
var a bool = true // Boolean
var b int = 5 // Integer
var c float32 = 3.14 // Floating point number
var d string = "Hi!" // String
Arrays in Go
Arrays are used to store multiple values of the same type in a single variable, instead of declaring separate variables for each value.
package main
import (
"fmt"
)
func main() {
//array_name := [Length]datatype{data}
array_name := [4]int{1, 2, 3, 4}
fmt.Println(array_name)
}
Arrays with inferred lengths
array_name := [...]int {1,3,4,4,44}
Access Elements of an Array
fmt.Println(array_name[0])
Change Elements of an Array
array_name[2] = 50
Find the Length of an Array
fmt.Println(len(array_name))
Slices in Go
Slices are similar to arrays but are more powerful and flexible.
Used to store multiple values of the same type in a single variable.
Creating a Slice
slice_name := []datatype{values}
myslice := []int{}
//code above declares an empty slice of 0 length and 0 capacity
In Go, two functions 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)
Create a Slice From an Array
var myarray = [length]datatype{values} // An array
myslice := myarray[start:end]
Create a Slice With The make() Function
slice_name := make([]type, length, capacity)
Accessing Elements of a Slice
fmt.Println(prices[0])
Change Elements of a Slice
prices[0] = 23 //previous
prices[0] = 34
fmt.Println(prices[0])
Append Elements To a Slice
slice_name = append(slice_name, element1, element2, ...)
Conditions in Go
Conditional statements are used to perform different actions based on different conditions.
The if-else Statement
if condition {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
The else-if Statement
if condition1 {
// code to be executed if condition1 is true
} else if condition2 {
// code to be executed if condition1 is false and condition2 is true
} else {
// code to be executed if condition1 and condition2 are both false
}
The Nested Statement
if condition1 {
// code to be executed if condition1 is true
if condition2 {
// code to be executed if both condition1 and condition2 are true
}
}
Loops in Go
- The
for
loop loops through a block of code a specified number of times.
For loop
package main
import ("fmt")
func main() {
for i:=0; i < 5; i++ {
fmt.Println(i)
}
}
The
continue
the statement is used to skip one or more iterations in the loop. It then continues with the next iteration in the loop.The
break
the statement is used to break/terminate the loop execution.
Functions in Go
A function is a block of statements that can be used repeatedly in a program.
Create a Function
func FunctionName() {
// code to be executed
}
Calling a Function
package main
import ("fmt")
func myMessage() {
fmt.Println("I just got executed!")
}
func main() {
myMessage() // call the function
}
Parameters and Arguments
func FunctionName(param1 type, param2 type, param3 type) {
// code to be executed
}
Return Values
func FunctionName(param1 type, param2 type) type {
// code to be executed
return output
}
Tutorial: Create a Go module
This tutorial's sequence includes seven brief topics that each illustrate a different part of the language.
Create a module
Write a small module with functions you can call from another module
Open a command prompt and cd to your home directory
cd
Create a greetings directory for your Go module source code.
mkdir greetings
cd greetings
- Start your module using the go mod init command
The
go mod init
the command creates a go. mod file to track your code's dependencies. So far, the file includes only the name of your module and the Go version your code supports. But as you add dependencies, the go. mod file will list the versions your code depends on. This keeps builds reproducible and gives you direct control over which module versions to use.
go mod init example.com/greetings
- In your text editor, create a file in which to write your code and call it greetings. go.
package greetings
import "fmt"
// Hello returns a greeting for the named person.
func Hello(name string) string {
// Return a greeting that embeds the name in a message.
message := fmt.Sprintf("Hi, %v. Welcome!", name)
return message
}
Calling your code from another module
Create a
hello
directory for your Go module source code. This is where you'll write your caller.After you create this directory, you should have both a hello and a greetings directory at the same level in the hierarchy, like so:
<home>/
|-- greetings/
|-- hello/
cd ..
mkdir hello
cd hello
Enable dependency tracking for the code you're about to write.
go mod init example.com/hello go: creating new go.mod: module example.com/hello
Write code to call the Hello
function, then print the function's return value
package main
import (
"fmt"
"example.com/greetings"
)
func main() {
// Get a greeting message and print it.
message := greetings.Hello("Akash")
fmt.Println(message)
}
For production use, you’d publish the
example.com/greetings
module from its repository (with a module path that reflected its published location), where Go tools could find it to download it. For now, because you haven't published the module yet, you need to adapt theexample.com/hello
module so it can find theexample.com/greetings
code on your local file system.To do that, use the
go mod edit
command to edit theexample.com/hello
module to redirect Go tools from its module path (where the module isn't) to the local directory (where it is).
go mod edit -replace example.com/greetings=../greetings
From the command prompt in the hello directory, run the
go mod tidy
command to synchronize theexample.com/hello
module's dependencies, adding those required by the code, but not yet tracked in the module.
go mod tidy
At the command prompt in the hello
directory, run your code to confirm that it works.
Hi, Akash. Welcome!
Reference
Go tutorial with a more advanced topics like Struct, Maps
I appreciate your reading, buddy. Please like, comment on, and share this post if you find it beneficial.
Connect with me on :