Explanation of how to declare and use variables and constants in Go.
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
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
In Go, constants are declared using the const
keyword followed by the constant name and value.
const pi = 3.14
Constants can also be declared with a data type.
const pi float64 = 3.14
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
- Declare and initialize multiple variables or constants in a single statement.
var name, age = "John Doe", 25
const pi, gravity = 3.14, 9.81
- Declare and initialize a variable or constant using shorthand notation.
name := "John Doe"
const pi = 3.14
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
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.
Top comments (0)