Variables in Go

Variables in Go

In Go, variables are used to store values and can be declared using the var keyword. The syntax for declaring a variable is:

var name type

where name is the name of the variable, and type is the type of data that the variable will store. For example:

var age int
var name string

You can also assign values to variables at the time of declaration using the = operator:

var age int = 20
var name string = "John Doe"

Alternatively, you can use shorthand syntax to declare and assign values to variables:

age := 20
name := "John Doe"

Go supports several built-in data types, including integers (int, uint, etc.), floating-point numbers (float32, float64, etc.), strings (string), and boolean values (bool).

It's also possible to declare multiple variables in a single line:

var x, y, z int

or

x, y, z := 1, 2, 3

It's a good practice to use descriptive names for your variables, as it makes the code more readable and maintainable.

Go also supports constants, which are values that cannot be changed once declared. Constants are declared using the const keyword:

const pi float64 = 3.1415926535
const message string = "Hello, World!"

Note that it's mandatory to specify the type of a constant, unlike variables, which Go can infer automatically.

Last updated