Variables and Constants: Declaration and Usage

avinashtechlvr

Avinash Chodavarapu

Posted on March 25, 2023

Variables and Constants: Declaration and Usage

Explanation of how to declare and use variables and constants in Go.

Image description

Go is a statically typed programming language that requires variables to be declared with a specific data type. Variables can be declared using the var keyword followed by the variable name and data type.



var age int



Enter fullscreen mode Exit fullscreen mode

Here, age is the variable name and int is the data type. Variables can also be initialized with a value at the time of declaration.



var age int = 25



Enter fullscreen mode Exit fullscreen mode

In Go, constants are declared using the const keyword followed by the constant name and value.



const pi = 3.14



Enter fullscreen mode Exit fullscreen mode

Constants can also be declared with a data type.



const pi float64 = 3.14



Enter fullscreen mode Exit fullscreen mode

There are multiple ways to declare variables and constants in Go:

  • Declare and initialize a single variable or constant in a single statement.


var age int = 25
const pi float64 = 3.14



Enter fullscreen mode Exit fullscreen mode
  • Declare and initialize multiple variables or constants in a single statement.


var name, age = "John Doe", 25
const pi, gravity = 3.14, 9.81



Enter fullscreen mode Exit fullscreen mode
  • Declare and initialize a variable or constant using shorthand notation.


name := "John Doe"
const pi = 3.14



Enter fullscreen mode Exit fullscreen mode

In Go, it is possible to use variables and constants in expressions and statements. Here is an example:



var radius float64 = 5.0
const pi float64 = 3.14

var circumference = 2 * pi * radius



Enter fullscreen mode Exit fullscreen mode

In this example, the variable circumference is assigned the value of 2 * pi * radius.

In summary, variables and constants are used to store and manipulate data in Go programs. Variables can be changed during the execution of a program, while constants cannot. To declare a variable or constant, we use the "var" or "const" keyword followed by the name and type/value. To use a variable or constant, we refer to its name in our code.

💖 💪 🙅 🚩
avinashtechlvr
Avinash Chodavarapu

Posted on March 25, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related