Hi Cherolyn,
A variable is a thing that can be set to a value, and the value can be changed. Constants have values that cannot be changed.
var a int
a = 1 // set a to 1
fmt.Println(a) // prints "1"
a = 2 // change the value of a to 2
fmt.Println(a) // prints "2"
Since a
was declared as an int
, it can have only an integer value. The type of a
is int
. We set a
to the value 1
, then print the value of a
. Then we change a
's value to 2
, and print that.
One very simple way to think about this is to imagine you have boxes and you want to organize stuff. You write a name on each box, then put things in the boxes. The boxes are like variables, and each has a name. The items in the boxes are like values of the variables.
An identifier is a name for a constant, variable, type, function, or other named thing in the program. Some examples:
var buyer string = "John"
In the above, “buyer” is an identifier. It refers to the variable buyer
. "John"
is a string. That is, the type of the variable buyer
is string
. (Specifically, when you see characters between double quotes, it is a literal string, as opposed to a variable of type string
). “John” is a value that is being used to initialize buyer
.
func main() {
Here, “main” is an identifier. It is the name of the function main()
.
Basically, identifiers are “words” that you use to name things. I put that in quotes because identifiers can contain digits and underscore (_) characters as well as letters. Keywords are special words in Go that are used for other things. They are not identifiers. Examples are const
, var
, int
, string
, for
, and switch
. You cannot use those to name things you create.
In the following,
favFood := "Italian"
favFood
is an identifier (a name for a program element) and a variable. By using the :=
operator, we are declaring it to be of the same type as "Italian"
, which we are using to initialize it. So favFood
is of string
type, and it is set to "Italian"
, which is a literal string, and a value.
So you can see that different words are used to identify things in different ways. It’s a bit like how in English, the word “running” is a word, a noun, and a present participle.