Golang For Beginners

Golang For Beginners

·

10 min read

Hey Guys, In this blog you will learn everything to get started with Golang by writing a simple CLI app - TICKET BOOKING FOR CONCERT, we will cover

  • Why Go?

  • Hello-world

  • Variables & constants

  • Formatted output

  • User Input

  • Scope Rules

  • Arrays & Slices

  • Loops

  • If-else & Switch statements

  • Functions

  • Packages

  • Goroutines


Why Go?

Go is one of the youngest languages which is developed by a set of developers in google in 2007. The simple reason is it's clean and easy. Go is designed to be simple, and built for a purpose, essentially, Go is great for beginners.

  • Go was designed to run on multiple cores and built to support concurrency

  • concurrency in Go is cheap and easy

  • simple and readable syntax dynamically typed languages like python

  • Efficient and Safety of a low level, statically typed languages like c++

  • simple syntax: Easy to learn, read and write code

Let us learn concepts by building a Ticket booking app for concert


HELLO-WORLD

let us welcome our users

package main  //package name
import "fmt"  //importing fmt format package for using in our program
func main()   //the program starts here
{
//Let us welocme the user by writing welcome to our concert
      fmt.Println("welcome to our concert") 
      fmt.Println("Get ur tickets here to the concert")
// Go praograms are organized into packages 
//"fmt" is one of these,which you can use by importing it 
      fmt.Println(43)
}

Variables and Constants

Instead of mentioning generally as a concert, here we are going to specify the concert name, let's say GO CONFERENCE.

package main  //package name
import "fmt"  //importing fmt format package for using in our program
func main()   //the program starts here
{
    var concertname string //declaration
    concertname = "GO CONFERENCE"
    //OR
    var concertname string ="GO CONFERENCE" //initialization 
    //OR
    concertname := "GO CONFERENCE"  // we can specify in these many ways 

    var totalTickets int = 50 // or totalTickets := 50
    const totalTickets int = 50 //here we cannot update or modify the value in any place in the program  once initialized

Formatted Output


a := 10
b := 10.0
c := true
fmt.Println("the value  of a is " +a+"and the value of b is " +b+"the value of c is "+c) //not an best practise instead format it .

// formatting the output 

fmt.Printf("%v is the value of a and the data type of %v is %T\n",a,a)
fmt.Printf("%v is the value of b and the data type of %v is %T\n",b,b)
fmt.Printf("%v is the value of c and the data type of %v is %T\n",c,c)

User input

Let's get the user's first name, lastname, email adress, no of tickets needed for concert for sending the booking confirmitation in email or for printing ticket .

//Lets say the user needs this many ticket for concert so user must enter the no of tickets so we need to get user input data in go lang it's simple

//uint is an data type ie. unsigned integer the remaing tickets cannot be negative so we're using uint
package main

import (
    "fmt"
)

func main() {

    concertname := "GO CONFERENCE"
    var totalTicketsAvailable uint = 50
    var RemainingTickets uint = 50
    var firstName string
    var lastName string
    var email string
    var usertickets uint
    var bookings []string
    for {
        fmt.Printf("Hey  Welcome to our  %v\n", concertname)
        fmt.Printf("Hey Total TIckets for concert is  %v\n", totalTicketsAvailable)
        fmt.Println("Enter your first name")
        fmt.Scan(&firstName)
        fmt.Println("Enter your Last name")
        fmt.Scan(&lastName)
        fmt.Println("Enter your email")
        fmt.Scan(&email)
        fmt.Println("Enter the total no of tickets needed")
        fmt.Scan(&usertickets) 
        RemainingTickets -= usertickets
        bookings = append(bookings, firstName+""+lastName)

        fmt.Printf("Hey %v %v, Welcome to our  %v\n", firstName, lastName, concertname)
        fmt.Printf("Total tickets you have booked %v,remaing tickets availabe for %v is %v\n", usertickets, concertname, RemainingTickets)
        fmt.Printf("Confirmation email has been sent to %v\n", email)
        totalTicketsAvailable = RemainingTickets
    }
}

Scope rules

package main
import "fmt"
// if we declare variables in this scope ie before the main function 
// we can use update or modify anywhere in program
// for eg 
var a int = 10
func main(){
 fmt.Println(a) //this will print 10
 a = 20
 fmt.Println(a) //this will print 20
 b = 20 
}
 fmt.Println(b) //this will give error because we cannot use the variables outside the block of code if declared inside the block of code

Arrays

An array is an collection of similar data type elements . Let's say we have to collect the details of the users who booked the tickets

var bookings [50]string  //for writing strings in Array
//Here we are going to store the userthe user's first name and last name 
package main

import "fmt"

func main() {
    var bookings [50]string //for writing strings in Array
    // Here we are going to store the userthe user's first name and last name
    firstName := "Go"
    lastName := "lang"
    bookings[0] = firstName + " " + lastName
    fmt.Printf("The details of the bookings %v\n",bookings[0])
    fmt.Printf("The details of the bookings %v\n",bookings)
}

Slices

  • Slice is an abstraction of an Array

  • Slices are more flexible and Powerful: variable-length or get an sub-array of its own

  • Slices are also index-based and have a size ,but is resized when needed

  • It's like ArrayList in java

Append - adds the elements at the end of the slice

Grows the slice uf a greater capacity is needed and returns the updated slices .

var bookings []string  //for writing strings in Slices
//Here we are going to store the userthe user's first name and last name 
package main

import "fmt"

func main() {
    var bookings []string //for writing strings in Array
    // Here we are going to store the userthe user's first name and last name
    firstName := "Go"
    lastName := "lang"
    var bookings []string
    bookings= append(bookings,firstName+""+lastName)
    fmt.Printf("The details of the bookings %v\n",bookings[0])
    fmt.Printf("The details of the bookings %v\n",bookings)
    fmt.Printf("the length of slice booking  is %v\n",len(bookings))
}

LOOPS

A loop statement allows us to execute code multiple times, in a LOOP

Unlike other languages we don't have while loop do while loops .only we use for loop

we want to create a constant loop so app will not exit

for {
    fmt.Println("Hello")  // loop will be executed infinite times 
}
package main

import (
    "fmt"
)

func main() {

    concertname := "GO CONFERENCE"
    var totalTicketsAvailable uint = 50
    var RemainingTickets uint = 50
    var firstName string
    var lastName string
    var email string
    var usertickets uint
    var bookings []string
    for {
        fmt.Printf("Hey  Welcome to our  %v\n", concertname)
        fmt.Printf("Hey Total TIckets for concert is  %v\n", totalTicketsAvailable)
        fmt.Println("Enter your first name")
        fmt.Scan(&firstName)
        fmt.Println("Enter your Last name")
        fmt.Scan(&lastName)
        fmt.Println("Enter your email")
        fmt.Scan(&email)
        fmt.Println("Enter the total no of tickets needed")
        fmt.Scan(&usertickets) // user input
        RemainingTickets -= usertickets
        bookings = append(bookings, firstName+""+lastName)

        fmt.Printf("Hey %v %v, Welcome to our  %v\n", firstName, lastName, concertname)
        fmt.Printf("Total tickets you have booked %v,remaing tickets availabe for %v is %v\n", usertickets, concertname, RemainingTickets)
        fmt.Printf("Confirmation email has been sent to %v\n", email)
        totalTicketsAvailable = RemainingTickets
    }
}

If-else and switch statement

conditional statements to check the condition

if condition {

// body part to be executed

}

else {

// body part to be executed

}

in our case we need to check if the remaing tickets is zero or not if its zero then we should end the for loop

if..else statements are very useful in many cases

package main

import (
    "fmt"
)

func main() {

    concertname := "GO CONFERENCE"
    var totalTicketsAvailable uint = 50
    var RemainingTickets uint = 50
    var firstName string
    var lastName string
    var email string
    var usertickets uint
    var bookings []string
    for {
        fmt.Printf("Hey  Welcome to our  %v\n", concertname)
        fmt.Printf("Hey Total TIckets for concert is  %v\n", totalTicketsAvailable)
        fmt.Println("Enter your first name")
        fmt.Scan(&firstName)
        fmt.Println("Enter your Last name")
        fmt.Scan(&lastName)
        fmt.Println("Enter your email")
        fmt.Scan(&email)
        fmt.Println("Enter the total no of tickets needed")
        fmt.Scan(&usertickets) // user input
        if(usertickets > RemainingTickets) {
              fmt.Printf("we only have %v tickets\n,so please enter valid no of tickets",RemainingTickets)
              continue
          }
        RemainingTickets -= usertickets
        bookings = append(bookings, firstName+""+lastName)

        fmt.Printf("Hey %v %v, Welcome to our  %v\n", firstName, lastName, concertname)
        fmt.Printf("Total tickets you have booked %v,remaing tickets availabe for %v is %v\n", usertickets, concertname, RemainingTickets)
        fmt.Printf("Confirmation email has been sent to %v\n", email)
        totalTicketsAvailable = RemainingTickets

    if(RemainingTickets==0) {
       fmt.Println("Our concert tickets are over, so come back next year")
        break
    }
  }
}

User Input Validation

Here we're going to check whether the user entered details are valid or not

  • Conditions like FIRSTNAME AND LASTNAME should contain atleast 2 character's

  • email adress must contain character '@'

isvalidFirstName := len(FirstName)>=2
isvalidLastName := len(LastName)>=2
isValidemail :=string.contains(email,'@')
isvaliduserTicket := usertickets > RemainingTickets && usertickets>0
package main

import (
    "fmt"
)

func main() {

    concertname := "GO CONFERENCE"
    var totalTicketsAvailable uint = 50
    var RemainingTickets uint = 50
    var firstName string
    var lastName string
    var email string
    var usertickets uint
    var bookings []string
    for {
        fmt.Printf("Hey  Welcome to our  %v\n", concertname)
        fmt.Printf("Hey Total TIckets for concert is  %v\n", totalTicketsAvailable)
        fmt.Println("Enter your first name")
        fmt.Scan(&firstName)
        fmt.Println("Enter your Last name")
        fmt.Scan(&lastName)
        fmt.Println("Enter your email")
        fmt.Scan(&email)
        fmt.Println("Enter the total no of tickets needed")
        fmt.Scan(&usertickets) // user input
        isvalidFirstName := len(FirstName)>=2 //here
        isvalidLastName := len(LastName)>=2
        isValidemail := string.contains(email,'@')
        isvaliduserTicket := usertickets > RemainingTickets && usertickets>0
if(isvalidFirstName && isvalidLastName && isValidemail &&   isvaliduserTicket) {

        RemainingTickets -= usertickets
        bookings = append(bookings, firstName)

        fmt.Printf("Hey %v %v, Welcome to our  %v\n", firstName, lastName, concertname)
        fmt.Printf("Total tickets you have booked %v,remaing tickets availabe for %v is %v\n", usertickets, concertname, RemainingTickets)
        fmt.Printf("Confirmation email has been sent to %v\n", email)
        totalTicketsAvailable = RemainingTickets
}

if(RemainingTickets==0) {
       fmt.Println("Our concert tickets are over, so come back next year")
       break
 }
else { 
       if !(isvalidFirstName && isvalidLastName && isValidemail && isvaliduserTicket) {
       fmt.Println("Enter the valid data")

      }
    }
  }
}

Functions

Encapsulate code into own container which logically belong there

Like variables name ,you should give a function a descriptive name

call the function by it's name whenever neccessary

The above code looks complicated do let's simply it

func greet(concertname string,totalTicketsAvailable uint) 
{
        fmt.Printf("Hey  Welcome to our  %v\n", concertname)
        fmt.Printf("Hey Total TIckets for concert is  %v\n", totalTicketsAvailable) 

}
func userinp(firstName string, lastName string, email string, usertickets uint) (string,string,string,uint)
{
        fmt.Println("Enter your first name")
        fmt.Scan(&firstName)
        fmt.Println("Enter your Last name")
        fmt.Scan(&lastName)
        fmt.Println("Enter your email")
        fmt.Scan(&email)
        fmt.Println("Enter the total no of tickets needed")
        fmt.Scan(&usertickets)
         return firstName,lastName,email,usertickets
}
func isvalidinput(firstName string, lastName string, email string, usertickets uint,RemainingTickets uint)(bool,bool,bool,bool) 
{
        isvalidFirstName := len(FirstName)>=2 //here
        isvalidLastName := len(LastName)>=2
        isvalidemail := string.contains(email,'@')
        isvaliduserTicket := (usertickets > RemainingTickets && usertickets>0)
return isvalidfirstName,isvalidLastName,isvalidemail,isvalidusertickets
}
func message(firstName string, lastName string, email string, usertickets uint,RemainingTickets uint,totalTicketsAvailable uint)
{
        fmt.Printf("Hey %v %v, Welcome to our  %v\n", firstName, lastName, concertname)
        fmt.Printf("Total tickets you have booked %v,remaing tickets availabe for %v is %v\n", usertickets, concertname, RemainingTickets)
        fmt.Printf("Confirmation email has been sent to %v\n", email)
        totalTicketsAvailable = RemainingTickets
  return totalTicketsAvailable
}
package main

import (
    "fmt"
    "strings"
)

func main() {

    concertname := "GO CONFERENCE"
    var totalTicketsAvailable uint = 50
    var RemainingTickets uint = 50
    var firstName string
    var lastName string
    var email string
    var usertickets uint
    var bookings []string
    for {
        greet(concertname, totalTicketsAvailable)
        firstName, lastName, email, usertickets := userinp(firstName, lastName, email, usertickets)

        isvalidfirstName, isvalidLastName, isvalidemail, isvalidusertickets := isvalidinput(firstName, lastName, email, usertickets, RemainingTickets)

        if isvalidfirstName || isvalidLastName && isvalidemail && isvalidusertickets {

            RemainingTickets -= usertickets
            bookings = append(bookings, firstName)
            fmt.Printf("The users booked are%v\n", bookings)
            message(firstName, lastName, email, usertickets, RemainingTickets, totalTicketsAvailable, concertname)
            totalTicketsAvailable = RemainingTickets
            if RemainingTickets == 0 {

                fmt.Println("Our concert tickets are over, so come back next year")
                break
            }

        }
    }
}
func greet(concertname string, totalTicketsAvailable uint) {
    fmt.Printf("Hey  Welcome to our  %v\n", concertname)
    fmt.Printf("Hey Total TIckets available for concert is  %v\n", totalTicketsAvailable)

}
func userinp(firstName string, lastName string, email string, usertickets uint) (string, string, string, uint) {
    fmt.Println("Enter your first name")
    fmt.Scan(&firstName)
    fmt.Println("Enter your Last name")
    fmt.Scan(&lastName)
    fmt.Println("Enter your email")
    fmt.Scan(&email)
    fmt.Println("Enter the total no of tickets needed")
    fmt.Scan(&usertickets)
    return firstName, lastName, email, usertickets
}
func isvalidinput(firstName string, lastName string, email string, usertickets uint, RemainingTickets uint) (bool, bool, bool, bool) {
    isvalidFirstName := len(firstName) >= 2 //here
    isvalidLastName := len(lastName) >= 2
    isvalidemail := strings.Contains(email, "@")
    isvaliduserTicket := usertickets <= RemainingTickets && usertickets > 0
    return isvalidFirstName, isvalidLastName, isvalidemail, isvaliduserTicket
}
func message(firstName string, lastName string, email string, usertickets uint, RemainingTickets uint, totalTicketsAvailable uint, concertname string) {

    fmt.Printf("Hey %v %v, Welcome to our  %v\n", firstName, lastName, concertname)
    fmt.Printf("Total tickets you have booked %v,remaing tickets availabe for %v is %v\n", usertickets, concertname, RemainingTickets)
    fmt.Printf("Confirmation email has been sent to %v\n", email)

}

Did you find this article valuable?

Support THARUN by becoming a sponsor. Any amount is appreciated!