rodriggj / Go

0 stars 0 forks source link

1.2 Introduction to Variables #2

Open rodriggj opened 2 years ago

rodriggj commented 2 years ago

Variable declaration

  1. Below is the syntax for Variable declaration in GO

  2. Incorporated into your GO application a variable declaration example would look like this:

  1. The first part of the syntax begins with a "Variable Declaration" with the GO Keyword var

  2. Next is the assignment of an alias for the variable, this is simply a variable name that you will recognize as a developer:

  3. There are "rules" associated with the naming of a variable

  1. Finally in GO language, variables are strongly typed meaning you must declare the type of variable format the data is. For example, an Int, String, or reference to another Object type created within GO. This is different than other languages such as Javascript &/or Python that DO NOT require variable type declaration.

  1. Variables must be initialized by a value or else GO will automatically define a default value. So you can see in this example we declared a variable speed but we never assigned an initial value for speed so when we run the program main GO assigns the value 0 to speed as a default for "int" types.

  1. The Order in the script is also relevant. GO will read the file top-down, so if you have a function that utilizes a variable -- the variable MUST BE declared PRIOR to being called in the function. This is different than Javascript, where "Hoisting" occurs and variables can be declared anywhere in the script without regard for sequencing.

  1. This is a conceptual way to think about what is happening when variables are created. When following the syntax, what happens is a place in memory is assigned with your variable name. This has a variable declaration, name, and data type assigned and GO will manage retaining this variable till modified or deleted. Any reference to this variable is simply a reference to a place in memory.