Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Data Types in Go
  • Go Keywords
  • Go Control Flow
  • Go Functions
  • GoLang Structures
  • GoLang Arrays
  • GoLang Strings
  • GoLang Pointers
  • GoLang Interface
  • GoLang Concurrency
Open In App
Next Article:
Short Variable Declaration Operator(:=) in Go
Next article icon

Short Variable Declaration Operator(:=) in Go

Last Updated : 17 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Short Variable Declaration Operator(:=) in Golang is used to create the variables having a proper name and initial value. The main purpose of using this operator to declare and initialize the local variables inside the functions and to narrowing the scope of the variables. The type of the variable is determined by the type of the expression. var keyword is also used to create the variables of a specific type. So you can say that there are two ways to create the variables in Golang as follows:

  • Using the var keyword
  • Using the short variable declaration operator(:=)

In this article, we will only discuss the short variable declaration operator. To know about var keyword you can refer var keyword in Go. You can also read the difference between var keyword and short variable declaration operator to get a proper idea of using both.

Syntax of using short variable declaration operator: 

variable_name := expression or value

Here, you must initialize the variable just after declaration. But using var keyword you can avoid initialization at the time of declaration. There is no need to mention the type of the variable. Expression or value on the right-hand side is used to evaluate the type of the variable.

Example: Here, we are declaring the variables using short declaration operator and we are not specifying the type of the variable. The type of the variable is determined by the type of the expression on the right-hand side of := operator. 

Go
// Go program to illustrate the use  // of := (short declaration  // operator)  package main  import "fmt"  func main() {      // declaring and initializing the variable       a := 30      // taking a string variable     Language: = "Go Programming"      fmt.Println("The Value of a is: ", a)     fmt.Println("The Value of Language is: ", Language)    } 

Output:

The Value of a is:  30 The Value of Language is:  Go Programming


 

Declaring Multiple Variables Using Short Declaration Operator (:=)

Short Declaration operator can also be used to declare multiple variables of the same type or different types in the single declaration. The type of these variables is evaluated by the expression on the right-hand side of := operator. 

Example: 

Go
// Go program to illustrate how to use := short  // declaration operator to declare multiple  // variables into a single declaration statement package main   import "fmt"  func main() {   // multiple variables of same type(int) geek1, geek2, geek3 := 117, 7834, 5685   // multiple variables of different types geek4, geek5, geek6 := "GFG", 859.24, 1234  // Display the value and  // type of the variables  fmt.Printf("The value of geek1 is : %d\n", geek1)  fmt.Printf("The type of geek1 is : %T\n", geek1)   fmt.Printf("\nThe value of geek2 is : %d\n", geek2)  fmt.Printf("The type of geek2 is : %T\n", geek2)   fmt.Printf("\nThe value of geek3 is : %d\n", geek3)  fmt.Printf("The type of geek3 is : %T\n", geek3)  fmt.Printf("\nThe value of geek4 is : %s\n", geek4)  fmt.Printf("The type of geek4 is : %T\n", geek4)   fmt.Printf("\nThe value of geek5 is : %f\n", geek5)  fmt.Printf("The type of geek5 is : %T\n", geek5)  fmt.Printf("\nThe value of geek6 is : %d\n", geek6)  fmt.Printf("The type of geek6 is : %T\n", geek6)   }  

Output:

The value of geek1 is : 117 The type of geek1 is : int  The value of geek2 is : 7834 The type of geek2 is : int  The value of geek3 is : 5685 The type of geek3 is : int  The value of geek4 is : GFG The type of geek4 is : string  The value of geek5 is : 859.240000 The type of geek5 is : float64  The value of geek6 is : 1234 The type of geek6 is : int


Important Points: 

  • Short declaration operator can be used when at least one of the variable in the left-hand side of := operator is newly declared. A short variable declaration operator behaves like an assignment for those variables which are already declared in the same lexical block. To get a better idea about this concept, let's take an example.
    Example 1: Below program will give an error as there are no new variables in the left-hand side of the := operator.
Go
// Go program to illustrate the concept // of short variable declaration package main  import "fmt"  func main() {        // taking two variables     p, q := 100, 200      fmt.Println("Value of p ", p, "Value of q ", q)      // this will give an error as      // there are no new variable      // on the left-hand side of :=     p, q := 500, 600          fmt.Println("Value of p ", p, "Value of q ", q) } 

Error:

./prog.go:17:10: no new variables on left side of := 
 

Example 2: In the below program, you can see that the line of code geek3, geek2 := 456, 200 will work fine without any error as there is at least a new variable i.e. geek3 on the left-hand side of := operator.

Go
// Go program to show how to use  // short variable declaration operator package main   import "fmt"  func main() {   // Here, short variable declaration acts  // as an assignment for geek1 variable  // because same variable present in the same block  // so the value of geek2 is changed from 100 to 200 geek1, geek2 := 78, 100  // here, := is used as an assignment for geek2  // as it is already declared. Also, this line  // will work fine as geek3 is newly created // variable geek3, geek2 := 456, 200  // If you try to run the commented lines,  // then compiler will gives error because  // these variables are already defined  // geek1, geek2 := 745, 956 // geek3 := 150  // Display the values of the variables  fmt.Printf("The value of geek1 and geek2 is : %d %d\n", geek1, geek2)                                               fmt.Printf("The value of geek3 and geek2 is : %d %d\n", geek3, geek2)  }  


Output:

The value of geek1 and geek2 is : 78 200 The value of geek3 and geek2 is : 456 200
  • Go is a strongly typed language as you cannot assign a value of another type to the declared variable. 
      Example:
Go
// Go program to show how to use  // short variable declaration operator package main   import "fmt"  func main() {       // taking a variable of int type     z := 50          fmt.Printf("Value of z is %d", z)          // reassigning the value of string type     // it will give an error     z := "Golang" }  

Error:

./prog.go:16:4: no new variables on left side of := 
./prog.go:16:7: cannot use "Golang" (type string) as type int in assignment 
 

  • In a short variable declaration, it is allowed to initializing a set of variables by the calling function which returns multiple values. Or you can say variables can also be assigned values that are evaluated during run time. 
    Example:
// Here, math.Max function return  // the maximum number in i variable i := math.Max(x, y)

Local Variables or Global Variables?

With the help of short variable declaration operator(:=) you can only declare the local variable which has only block-level scope. Generally, local variables are declared inside the function block. If you will try to declare the global variables using the short declaration operator then you will get an error.

Example 1: 

Go
// Go program to show the use of := operator // to declare local variables package main     import "fmt"    // using var keyword to declare   // and initialize the variable  // it is package or you can say   // global level scope  var geek1 = 900     // using short variable declaration  // it will give an error geek2 := 200     func main() {     // accessing geek1 inside the function  fmt.Println(geek1)    // accessing geek2 inside the function fmt.Println(geek2)         }  

Error:

./prog.go:15:1: syntax error: non-declaration statement outside function body 
 


Example 2:

Go
// Go program to show the use of := operator // to declare local variables package main     import "fmt"    // using var keyword to declare   // and initialize the variable  // it is package or you can say   // global level scope  var geek1 = 900      func main() {   // using short variable declaration  // inside the main function // it has local scope i.e. can't  // accessed outside the main function geek2 := 200     // accessing geek1 inside the function  fmt.Println(geek1)    // accessing geek2 inside the function fmt.Println(geek2)         }  

Output: 

900 200


 


Next Article
Short Variable Declaration Operator(:=) in Go

A

anshul_aggarwal
Improve
Article Tags :
  • Go Language
  • Go-Operators
  • Golang

Similar Reads

    Difference between var keyword and short declaration operator in Golang
    A variable is a storage location or place holder used for holding the value. It allows us to manipulate and retrieve the stored information. There are two ways to declare the variables in Golan which are as follows: var varName type = valuevarName := valueDifference between var keyword and short dec
    4 min read
    How to print struct variables data in Golang?
    A struct (Structure) is a user-defined type in Golang that contains a collection of named fields/properties which creates own data types by combining one or more types. Also, this concept is generally compared with the classes in object-oriented programming. A struct has different fields of the same
    2 min read
    Printing Struct Variables in Golang
    Suppose, we need to print the structure with its fields corresponding value. We can do this with the help of package fmt which implements formatted I/O with functions analogous to C's printf and scanf. Let's first try if we just print the structure, what will happen.  Go package main import ("f
    2 min read
    How to declare and access pointer variable in Golang?
    Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system. The memory address is always
    3 min read
    Different Ways to Find the Type of Variable in Golang
    Variable is a placeholder of the information which can be changed at runtime. And variables allow to Retrieve and Manipulate the stored information. There are 3 ways to find the type of variables in Golang as follows: Using reflect.TypeOf Function Using reflect.ValueOf.Kind() Function Using %T with
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences