Golang is syntactically similar to the C language and like C it is concise, clean and efficient. If you are familiar with C concepts it is easy, to begin with, the basics of golang. In this article, we will learn the basic concepts of golang.
Golang is referred to as a “simple” programming language. Anyone familiar with basic programming fundamentals can learn the basics in a few hours. Because of its simplicity, the entire language specification fits in just a few pages.
Let us now explore the dynamics.
Variable Declaration
The var statement declares a list of variables. In golang variable name comes first following with the data type. We can either declare a variable or a list of variables.
var(name,age,location) = ”Peter”, 20, ”London”
Initialisation
var( name = ”Peter”,
age = 20
Location = ”London”)
We can also declare variables by an implicit conversion using := shorthand.
Example:
a := 42 // a as int
name := “Genny” // name as string.
NOTE
A variable can be any type including functions :
actions := func() {
Statement
}
actions() // variable called as a function
Constants
The const keyword is used to make variables constant.
Features -
> No := is used to declare const keywords.
> An untyped const takes the type needed by its context.
Examples
const pi = 3.14
const(
X = 10
Y = 20.08
Str = ”Ninja” )
Print in go
We can use these 3 functions in golang for printing constant, variables and messages. They are present in the ‘fmt’ package.
print – To print in the same line
println – To print in the new line
printf – To print one or more than one values in a specified manner
Example:
package main
import "fmt"
func main() {
name := "Harry"
age := 6
fmt.Printf("%s is %d years old", name, age)
// Printing variables within the string
// Output - Harry is 6 years old
}
FUNCTIONS:
Golang has a unique way of dealing with functions. It has a main() function by default from where the execution begins. The func keyword is used to declare functions.
Synatax:
func function-name(parameter-list) return-type(if any){
statement(s)
}
Characteristics of Golang
- The function can return one or multiple values.
- The first function name is declared then the type of function.
- In case there are multiple values to be returned, declare the variables and at the end of the code, we simply write ‘return’ or we can return values separated by ‘,’.
- It is best practice to use named return parameters because they often cause more confusion than they save time or help clarify your code.
Example:
Returning a single parameter
package main
import "fmt"
// Function definition that returns sum of two numbers
func add(x, y int) int {
return x + y
}
func main() {
fmt.Println(add(42, 13)) // Adds two numbers
}
Returning multiple parameters
package main
import “fmt”
// function return addition and subtraction of two numbers
func do_it(x,y int) (add,mul int){
add := x+y
mul := x*y
return add,mul // multiple values returned
}
Func main(){
addition, multi:= do_it(30,20)
// addition holds the add value and multi holds mul
}
POINTERS
A pointer is a variable that is used to store the memory address of another variable. Go has pointers like C but no pointer arithmetic. By default, arguments are passed by value in functions.
Declaring a pointer -
var pointer-name *data-type
Example
var s *string // Pointer of type string that stores the memory address of string variables
Initialisation -
// Normal variable declaration
var a = 45
// Initialisation of variable s with a memory address of variable a
var s *int = &a
MAPS
Maps in golang are similar to “dictionaries” and “hashmaps” in other languages. It is popular because it provides fast lookups and values that can retrieve, update or delete with the help of keys.
Simple: In this method, the map can be created directly by the following.
Syntax:
// An Empty map
map[Key_Type]Value_Type{}
// Map with key-value pair
map[Key_Type]Value_Type{key1: value1, ..., keyN: valueN}
Example - var mymap map[int]string
By default a map is nil.
Initialising map using map literals: Using this method we initialise a map with : separated key-value pairs.
Example:
package main
import "fmt"
func main() {
// creating and initializing a map
var map_1 map[int]int
// nil means empty map
if map_1 == nil {
fmt.Println("True")
} else {
fmt.Println("False")
}
map_2 := map[int]string {
90: "Dog",
91: "Cat",
92: "Cow",
93: "Bird",
94: "Rabbit",
}
fmt.Println("Map-2: ", map_2)
}
Using make function: The inbuilt function make() can also be used to create a map. Pass the key type, value type and initial capacity(optional) of the map.
Syntax:
make(map[Key_Type]Value_Type, initial_Capacity)
make(map[Key_Type]Value_Type)
Example
package main
import "fmt"
func main() {
// Creating and initializing the empty map Using var keyword
var map_1 map[int]int
if map_1 == nil {
fmt.Println("True")
} else {
fmt.Println("False")
}
// Creating and initializing a map and Using shorthand declaration
map_2 := map[int]string{
90: "Dog",
91: "Cat",
92: "Cow",
93: "Bird",
94: "Rabbit",
}
fmt.Println("Map-2: ", map_2)
}
SLICES
Slices take over arrays to give a more general, powerful, and convenient interface to sequences of data. For this reason, most programming in Go is done with slices rather than simple arrays. If you assign one slice to another, they will point to the same slice because slices hold references to an underlying array. If a slice is passed to a function the changes made to slice inside the function will reflect in the original slice too.
Slices can be resized.
Example:
package main
import "fmt"
func main() {
m_slice := []int{2, 3, 5, 7, 15, 13} // Declaring a slice
fmt.Println(m_slice) // [2 3 5 7 15 13]
}
Slicing the slice -
You will understand slicing with the help of this example.
package main
import "fmt"
func main() {
m_slice := []int{2, 3, 5, 7, 15, 13}
fmt.Println(m_slice) // [2 3 5 7 15 13]
// Takes the element indexed from 1 to 3 ie, leaving 4th index
fmt.Println(m_slice[1:4]) // [3 5 7]
// missing low index implies 0
fmt.Println(m_slice[:3]) // [2 3 5]
// missing high index implies len(s)
fmt.Println(m_slice[4:]) // [15 13]
}
Structure
It is a user defined data type that contains multiple types (data members and member functions) into a single type.
Example:
package main
import "fmt"
// Defining a struct type
type Address struct {
Name string
city string
Pincode int
}
func main() {
// All the struct fields are initialized with their zero value
var a Address // The variable a is struct type here
fmt.Println(a)
// Declaring and initializing a struct using a struct literal
a1 := Address{"Akshay", "Dehradun", 3623572}
fmt.Println("Address1: ", a1)
// Fields are named while initializing a struct
a2 := Address{Name: "Anikaa", city: "Ballia", Pincode: 277001}
fmt.Println("Address2: ", a2)
// Uninitialized fields have zero-value
a3 := Address{Name: "Delhi"}
fmt.Println("Address3: ", a3)
}
This was all about the basics of go. The loops, conditional statements and switch work similar to C language. The only difference is a switch in Golang as one case can handle multiple values. Concurrent programming is a large topic but has most of its own benefits. Concurrency in Golang has the ability for functions to run independently of each other.
To explore more articles, click here.
Mansi Agarwal
Leave a Reply