The Golang stands for Google Language which is created by Google  


Uses of Golang :

-> Web programming

-> Kubernetes, docker underlying architecture 

-> Network models architecture


1. Golang uses compiler to compile the code into byte language and then executes




2. Sample Hello World! program in Golang 

package main

import "fmt"

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

Output




To execute the Go program we use following command 

Command: go run <go_file_name>

ex: Here our Hello world program is written in the file named "main.go" so 

we use go run main.go to execute the program

Link : https://github.com/ap0072/golang/blob/main/prg0.go



4. Golang is a static type language but it feels like dyna

Go (Golang) is a statically typed language, meaning variables are usually required to have their types explicitly defined. 

However, it can feel like a dynamically typed language due to its implicit type inference. In Go, when you use shorthand notation to declare a variable (e.g., `s := "Prasanth"`), the compiler automatically infers the type of the variable based on the assigned value, without explicitly requiring a type declaration. 

In this case, the variable `s` is automatically inferred to be of type `string` because the assigned value is a string. 

ex: s := "Prasanth" (declaring a variable in shorthand notation in Golang

Thus, while Go enforces type safety and static typing, its type inference feature makes it seem more flexible, similar to dynamic typing.



5. Data Type in Golang

Mainly there are four different data types

Here's the information in a tabular format:


| **Data Type** | **Memory Size** | **Use Case** |

|----------------|-----------------------|---------------------------------------|

| `int` | 4 bytes (or 8 bytes) | For integers like 1, 2, 3 |

| `float32` or `float64` | 4 bytes (or 8 bytes) | For floating-point values like 1.23, 0.45 |

| `string` | 16 bytes | For string values like "India", "Delhi" |

| `bool` | 1 byte | For boolean values like true or false |



6. Declaring a variable in Golang

Method 1:

var <variable-name> <data-type> = <value>

ex: var name string = "prasanth"

Method 2:

var <variable-name1>,<variable-name2>  <data-type> = <value1>,  <value2>

ex: var username,place string = "prasanth", "Hyderabad"

Method 3:

var (

<variable-name1> <data-type> = <value1>

<variable-name2> <data-type> = <value2>

)

ex: var( 

username string = "prasanth"

pincode int     =  "500032"

)

Method 4: Short-hand decalration

 <variable> := <value>

ex:  s := "Prasanth"



7. Different ways of printing variables using Print, Printf, Println functions

In general, we import all kinds of print functions from fmt package 


Type 1: using Print function 

fmt.Print(<variable-name>)


Type 2: using Println function 

we use this type for printing all variables in new line

fmt.Println(<variable-name>)


Type 3: using Printf function to print values of variables in different formats 


  • %v   -> default format for printing the strings
  • %s   -> for plain string values
  • %d   -> for the decimal integer values
  • %f    -> floating numbers
  • %.2f -> floating numbers upto two decimal places
  • %t    -> boolean (true or flase) values
  • %q   -> to print string with quotes
  • %T   -> gives the type of string


ex: 

// Using format specifier Printf to print in different formats
package main

import "fmt"

func main() {
    var (
        name   string = "Prasanth"
        grades int    = 75
    )
    fmt.Printf("hi, everyone. I am %v and I got %d/100 in maths\n ", name, grades)

    {
        var blood_group string = "O+ve"
        fmt.Printf("hi, everyone. I am %s and I got %d/100 in maths and my blood group
is %q", name, grades, blood_group)

    }

}

Output:



 

8. Variable Scope 

In general any variable present in the outer block can be accessed in the inner block where as any variable inside the inner block cannot be accessed in the outer block


{

outer block

{

inner block

}


package main

import "fmt"

func main() {
// outer block
    var (
        name   string = "Prasanth"
        grades int    = 75
    )
    fmt.Printf("hi, everyone. I am %v and I got %d/100 in maths\n ", name, grades)

    {
// inner block
        var blood_group string = "O+ve"
        fmt.Printf("hi, everyone. I am %s and I got %d/100 in maths and my blood group
is %q", name, grades, blood_group)

    }

}


this will execute without any error 



but 

package main

import "fmt"

func main() {
    //outer block
    var (
        name   string = "Prasanth"
        grades int    = 75
    )
    fmt.Printf("hi, everyone. I am %v and I got %d/100 in maths and my blood group is
%q\n ", name, grades, blood_group)

    {
        //inner block
        var blood_group string = "O+ve"
        fmt.Printf("hi, everyone. I am %s and I got %d/100 in maths and my blood group
is %q", name, grades, blood_group)

    }

}



There will be an error at Print statement as there is no variable found with name "blood_group" though we have given 3 variables name, grades, blood_group to print in the outer block so output will be



 

In general,  we have two type of variables 

  1. Local variable
  2. Global Variable


The local variables are declared within a function and scope of this variable will be with in that function only

 where as global variables are declared above all the functions so the scope of this variable will be in whole program 


package main

import "fmt"

var a string = "global" // declaring a global variable

func main() {

    b := "local"    // declaring a local variable

}



10. Zero values


If any value is not assigned to any variable then zero values or default values will be assigned as follows

var i int will be auto assign by zero or default value of 0

var name string will be auto assign by zero or default value of " "

var f float64 will be auto assign by zero or default value of 0.0000

var b bool  will be auto assign by zero or default value of false


// Comparison Operators i.e ==, !=, <, <=, >, >=
package main

import "fmt"

func main() {
    var i int

    var name string

    var f float32

    var b bool

    fmt.Println(i)
    fmt.Printf("%q\n", name)
    fmt.Printf("%.2f\n", f)
    fmt.Println(b)

}

Output:






11. Input to program


In order to give input to any Go program, we use "Scanf"  or "Scan" function from fmt package to take the inputs and store them in the respective variables

Using Scanf function

// Using Scanf function to take the input from user
package main

import "fmt"

func main() {
    var name string
    var phoneNumber int

    fmt.Print("Enter your name and number ")
    fmt.Scanf("%s %d", &name, &phoneNumber) // Use Scan here

    fmt.Printf("Hi, everyone. I am %s and my phone number is %d", name, phoneNumber)

}

Output:






Additionally this Scanf function will return two values 

-> count, 

-> error 


where count gives how many successful variables are assigned with input without any errors

whereas for the error value we will get no of errors occurs while assigning a value to variable during Scanf function

count, error := fmt.Scanf("%s %d", &name, &grades)

// Using Scanf function to take the input from user
package main

import "fmt"

func main() {
    var name string
    var phoneNumber int

    fmt.Print("Enter your name and number ")
    //fmt.Scanf("%s %d", &name, &phoneNumber) // Use Scan here
    count, errors := fmt.Scanf("%s %d", &name, &phoneNumber)

    fmt.Printf("Hi, everyone. I am %s and my phone number is %d \n", name, phoneNumber)
    fmt.Printf("Printing the count %v and error %v occur during taking input using
Scanf function", count, errors)

}

Output:






Using Scan function

This Scan function is more flexible when compared to Scanf function as we don't need to specify the format specifier while taking input from the user 

package main

import "fmt"

func main() {
    var name string
    var phoneNumber int

    fmt.Print("Enter your name: ")
    fmt.Scan(&name) // Use Scan here

    fmt.Print("Enter your phone number: ")
    fmt.Scan(&phoneNumber) // Use Scan here

    fmt.Printf("Hi, everyone. I am %s and my phone number is %d\n", name, phoneNumber)
}

Output:







12. Finding the type of variable


We can use the %T format specifier or reflect.TypeOf() function to get the type of any variable in Go progam


package main

import (
    "fmt"
    "reflect"
)

func main() {

    var name string = "Prasanth"
    //var grades int = 10
    fmt.Printf("hi, everyone. I am %v and type of variable name is %T \n", name, name)
    fmt.Printf("hi, everyone. I am %v and type of variable name is %v", name,
reflect.TypeOf(name))

}

Output:






Note: both lines are printing same output as we can use both the functions to know the type of the variable


13. Type casting in Go lang

Converting one data type into other data type which we also called "Type casting"

we use strconv package to convert one data type (string) to other data type (Integer)


we use following functions 

-> convert int to float    -  using float32(<integer-variable>) or float64(<integer-variable>)

-> convert int to string  -  using strconv.Itoa(<integer-variable>)

-> convert string to int  -  using strconv.Atoi(string-variable)


package main

import (
    "fmt"
    "strconv"
)

func main() {

    var strname string = "200"
    var intgrades int = 10

    gradesinstring := strconv.Itoa(intgrades) // converting the integer variable to
String variable
    fmt.Printf("hi, everyone grades are now printing in string format %v and type of
this variable is now %T \n", intgrades, gradesinstring)

    nameininteger, errors := strconv.Atoi(strname) / converting the String variable to
integer variable
    fmt.Printf("hi, everyone. my  string variable  is now converted into integer
variable with value %v %T \n", nameininteger, nameininteger)
    fmt.Printf("%v %T", errors, errors)

}

Output:





14. Declaring constants in Golang

A constant variable means the value of variable remains same and it wont change once declared

We use keyword "const" to declare any variable as constant variable

declaration

const <var-name> <data-type> = <value>

const <var-name> = <value> 

// In this above case the compiler will automatically assign the data type of variable dynamically based on the value assigned to this variable


Ex: Finding Area of Triangle

we know the area of triangle is 1/2*b*h, given base and height of the triangle.

// Using the Costant variables
package main

import (
    "fmt"
)

func main() {
    var base float32
    var height float32
    const initial float32 = 0.5 // decalring the constant variable "initial"

    fmt.Println("Enter the base of the triangle: ")
    fmt.Scan(&base) // Use %f for float32

    fmt.Println("Enter the height of the triangle: ")
    fmt.Scan(&height) // Use %f for float32

    formula := initial * base * height // Using Shorthand notation for declaring
variable formula
    fmt.Printf("Area of the Triangle is %.2f\n", formula) // Print the area
}

Output




15. Operators in Golang

In General, we use different kinds of operators such as 

Comparison Operators

  • ==
  • !=
  • <=
  • >=
  • <
  • >

to compare two values same data type or different data type as well

Ex: To compare two  variables with above mentioned operators such as

// Comparison Operators ==, !=, <, <=, >, >=
package main

import "fmt"

func main() {
    var name string = "India"
    var name_2 string = "USA"
    var a, b, c int = 1, 2, 3
    fmt.Printf("The boolean value of %d == %d is %t \n", a, b, a == b)
    fmt.Printf("The boolean value of %d != %d is %t \n", a, b, a != b)
    fmt.Printf("The boolean value of %d < %d is %t \n", a, b, a < b)
    fmt.Printf("The boolean value of %d <= %d is %t \n", a, b, a <= b)
    fmt.Printf("The boolean value of %v == %v is %t \n", name, name_2, name == name_2)
    fmt.Printf("The boolean value of %v != %v is %t \n", name, name_2, name < name_2)
    fmt.Printf("The boolean value of %d > %d is %t \n", b, c, b > c)
    fmt.Printf("The boolean value of %d >= %d is %t \n", b, c, b >= c)

}

Output


Arithmetic Operators

The operators used between two operands or two integer variables to do various mathematical operations such as 

  1. addition ( + )
  2. subtraction ( - )
  3. multiplication ( * )
  4. division ( / )
  5. modulus  ( % )
  6. increment by value one ( ++ )  
  7. decrement by value one  ( --)
Note: Increment and decrement operators also known as unary operators as they require only one operand 

Ex: 

// Arthimetic Operators
package main

import "fmt"

func main() {
    var a int = 10
    var b int = 2
    fmt.Printf("The  sum of %d + %d is %d \n", a, b, a+b)
    fmt.Printf("The  difference of %d - %d is %d \n", a, b, a-b)
    fmt.Printf("The  multiplication of %d * %d is %d \n", a, b, a*b)
    fmt.Printf("The  division of %d / %d is %d \n", a, b, a/b)
    fmt.Printf("The  modulus of %v %% %v is %d \n", a, b, a%b)
    // we cannot increment the value directly. First we need to do increment operation
    // and then assign to new variable
    c := a
    c++
    d := c
    fmt.Printf("The  value of %d after increment by value one is %d \n", a, d)
    // we cannot increment the value directly. First we need to do increment operation
    // and then assign to new variable
    e := a
    e--
    f := e
    fmt.Printf("The  value of %d after decrement by value one is %d \n", a, f)

}

Output:










Logical Operators

The operators used between two operands  to do various logical operations such as 

1. Logical AND  ( && )
2. Logical OR     (   ||   )
3. Logical NOT  (    !  )

Ex:

// Logical Operators
package main

import "fmt"

func main() {
    var a int = 10
    var b int = 2
    fmt.Printf("the boolean value of %d > %d , is %t \n", a, b, a > b)
    fmt.Printf("the boolean value of %d < %d , is %t \n", a, b, a < b)
    //using Logical and operator - &&
    c := (a > b) && (a < b)
    fmt.Printf("the boolean value of (%d > %d) and (%d < %d) , is %t \n", a, b, a, b, c)
    //using Logical or operator - ||
    d := (a > b) || (a < b)
    fmt.Printf("the boolean value of (%d > %d) or (%d < %d) , is %t \n", a, b, a, b, d)
    //using Logical not operator - !
    fmt.Printf("the boolean value of not of false , is %t \n", !c)
    fmt.Printf("the boolean value of not of true , is %t \n", !d)
}

Output:











Assignment Operators

The operators used between two operands  to do various assignment operations such as 

  1. addition and assignment            (  +=  )
  2. subtraction and assignment       (  -=    )
  3. multiplication and assignment  (  *=   )
  4. division and assignment            (  /=    )
  5. modulus and assignment           (  %=  )

Ex.
// Arthimetic Operators
package main

import "fmt"

func main() {
    var a int = 10
    var b int = 2
    {
        c := a
        d := b
        c += d     // applying the addition and assignment operation
        fmt.Printf("The  value of %d += %d is %d \n", a, b, c)
    }
    {
        c := a
        d := b
        c -= d    // applying the subtraction and assignment operation
        fmt.Printf("The  value of %d -= %d is %d \n", a, b, c)
    }
    {
        c := a
        d := b
        c *= d     // applying the multiplication and assignment operation
        fmt.Printf("The  value of %d *= %d is %d \n", a, b, c)
    }
    {
        c := a
        d := b
        c /= d    // applying the division and assignment operation
        fmt.Printf("The  value of %d /= %d is %d \n", a, b, c)
    }
    {
        c := a
        d := b
        c %= d    // applying the modulus and assignment operation
        fmt.Printf("The  value of %d %%= %d is %d \n", a, b, c)
    }

}


Note: Here, I have created sub blocks for each assignment operator because, If I print the value of a after applying the assignment operation, the value of a will be changed 

so in order to maintain the original values of a , b,  I have taken two more extra variables c , d and assign the values of a, b to them and done the required assignment operations in each sub block  and printed the values of a, b and the result of value after applying the assignment operation with help of c, d 

Output:












Bitwise Operators

The operators used between two operands  to do various bit to bit operations such as 

  1.  Bitwise AND ( & )
  2.  Bitwise OR    ( |  )
  3.  Bitwise XOR ( ^ )
  4.  Left Shift       ( << )
  5.  Right Shift     ( >> )

Bitwise AND Operation

Here the result of two bits will become 1 if both bits equals to 1 other wise the result will be 0

12:         00001100 (Binary represenation of 12)
25:         00011001 (Binary represenation of 25)
                        --------------
bitwise AND : 00001000 (Binary represenation of 8)
                        --------------


Bitwise OR Operation

Here the result of two bits will become 1 if any of the bit equals to 1 other wise the result will be 0

12:          00001100 (Binary represenation of 12)
25:          00011001 (Binary represenation of 25)
                        --------------
bitwise OR :   00011101 (Binary represenation of 29)
                        --------------

Bitwise XOR Operation

Here the result of two bits will become 1 if both of the bits are opp to each other other wise the result will be 0

12:              00001100 (Binary represenation of 12)
25:              00011001 (Binary represenation of 25)
                          --------------
bitwise XOR :     00010101 (Binary represenation of 21)
                          --------------

Bitwise Leftshift Operation

we will shift the bits position to left hand side by specific number such as 

212: 11010100 (Binary represenation of 212)

After leftshift  by 1 positions, then 11010100 will becomes  110101000   as  follows











here all the positions are shifted by 1 and the remaining with position will be filled with 0's. hence the value of left shift operation by 1 for 212 becomes 424


Bitwise Rightshift Operation

we will shift the bits position to Right hand side by specific number such as 

12: 00001100 (Binary represenation of 12)

After rightshift  by 2 positions, then 00001100 will becomes  00000011   as  follows






here the last two positions(00) are discarded( ignored )  as we are shifting right by 2 positions and remaining positions will be filled with 0's


Note: If you observe in the Left shift operation we are shifting the bits to left side by certain no.of.positions and adding the 0's in the remaining positions,

where as in the Right Shift operation, we will be discarding the postions after shifting and filling the remaining positions in the left hand side with 0's 

that's why we are getting the decreased value for Right shift operation, where as increased value for left shift operation


// Bitwise Operators
package main

import "fmt"

func main() {
    var a int = 12
    var b int = 25

    //using Bitwise and operator - &
    c := a & b
    fmt.Printf("the bitwise AND operator value of %d , %d is %d \n", a, b, c)

    //using Bitwise or operator - |
    d := a | b
    fmt.Printf("the bitwise OR operator value of %d , %d is %d \n", a, b, d)

    //using Bitwise xor operator - |
    e := a ^ b
    fmt.Printf("the bitwise XOR operator value of %d , %d is %d \n", a, b, e)

    //using Bitwise Left shift operator - |
    f := 212 << 1
    fmt.Printf("the bitwise Left shift operation on value %d, with position 1 is %d \n", 212, f)

    //using Bitwise Left shift operator - |
    g := 12 >> 2
    fmt.Printf("the bitwise Right shift operation on value %d, with position 2 is %d \n", a, g)

}


Output:
















Comments

  1. Please find all the source code at my github website https://github.com/ap0072/golang

    ReplyDelete

Post a Comment