Logo

Developer learning path

Go

Variables in Go

Variables

67

#description

Sure, I'd be happy to explain variables in Go!

In Go, variables are used to store values which can be accessed and manipulated throughout the program. Declare a variable in Go using the var keyword, followed by the variable name and its type.

For example, to create an integer variable named age, you could use the following code:

                    
var age int
                  

This creates a variable named age of type int. By default, its value is 0.

You can also assign a value to a variable at the time it is declared, like this:

                    
var age int = 25
                  

This creates a variable named age and sets its initial value to 25.

Go also supports type inference, which means you can let the compiler deduce the variable type for you. To do this, you can use the := operator instead of var.

For example:

                    
age := 25
                  

This creates a variable named age and sets its initial value to 25, with the compiler automatically deducing that the variable's type is int.

Variables can also be assigned new values later in the program.

For example:

                    
age = age + 1
                  

This statement increments the value of the age variable by 1.

Overall, variables in Go are used to store values throughout the program, and can be declared, assigned, and manipulated in a variety of ways using the var keyword and other operators.

March 27, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.