Golang program to depict short variable declaration operator(:=)


In this golang article, we will write Go language programs to depict short variable declaration operator using var keyword and variable declaration.

In shorthand variable, initialization is done at the time of declaration where it’s not necessary in var keyword. Here, we will use a string method, as well as a count variable method to depict short variable declaration.

Algorithm

  • Step 1 − Import the required packages in the program

  • Step 2 − Create a main function

  • Step 3 − In the main use short variable declaration to create strings

  • Step 4 − Print the strings created via shorthand declaration using Println function from the fmt package

Example 1

In this Example, we will create a main and in that function, we will create a string using short variable declaration. Later, the string will be printed on the console.

package main

import "fmt"

func main() {
   greet := "Hello, alexa!" 
   fmt.Println(greet)
}

Output

Hello, alexa!

Example 2

In this Example, name and age are created using short variable declaration and printed on the console with the help of format specifiers.

package main

import "fmt"

func main() {
   name, age := "Varun", 40 
   fmt.Printf("%s is %d years old\n", name, age)
}

Output

Varun is 40 years old

Example 3

In this illustration, a count variable is initialized with 1 using short variable declaration. Then, it is checked if the value stored in count is greater than 0 the success statement will be printed using short variable otherwise failure statement will be printed.

package main

import "fmt"

func main() {
   count := 1 
   if count > 0 {
      state := "There are some items." 
      fmt.Println(state)
   } else {
      state := "There are no items." 
      fmt.Println(state)
   }
}

Output

There are some items.

Example 4

In this Example, we will write a Go language program to depict short variable declaration using the new keyword.

package main

import "fmt"

func main() {
   Name := new(string)
   *Name = "Ritika"
   Age := new(int)
   *Age = 21
   Height := new(int)
   *Height = 165

   fmt.Println(*Name, "is", *Age, "years old and", *Height, "cm tall.")
}

Output

Ritika is 21 years old and 165 cm tall.

Conclusion

We compiled and executed the program of depicting short variable declaration. In the first Example, we printed a greeting statement using shorthand declaration, in the second Example, we used format specifiers to print the statements created through shorthand declaration, in the third Example, a count variable is created which is later manipulated to perform certain operations and in the fourth Example we used a new keyword.

Updated on: 03-May-2023

59 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements