golang tutorial - Golang Global Variables | Golang Var | Go Global Variable - golang - go programming language
Variable Definition in Go:
- Variable is the name given to a memory location to store a value of a specific type.
Below is the syntax of variable declaration
- Here, optional_data_type is a valid Go data type including
- byte,
- int,
- float32,
- complex64,
- boolean or any user-defined object, etc.,
- variable_list may consist of one or more variables or identifier names separated by commas. Some valid declarations are shown here:
- var a,b,c are of integer type
- var x and ch is of type byte.
- Variables can be initialized (assigned an initial value) in their declaration. The type of variable is automatically judged by the compiler based on the value passed to it. The initializer consists of an equal sign followed by a constant expression as follows:
Some examples are:
Read Also
Python Global variable- Variables declared without a corresponding initialization are zero-valued. For example, the zero value for an int is 0.
- var declares 1 or more variables.
- The := syntax is shorthand for declaring and initializing a variable, For e.g. var f string = "short" in this case.
Output :
Static type declaration
- A static type variable declaration will have the declaration clearly.
- A variable declaration has its meaning at the time of compilation only, compiler needs actual variable declaration at the time of linking the program.
Example
Output :
Read Also
Scope variable in c++Dynamic type declaration / Type Inference
- A dynamic type variable declaration requires compiler to interpret the type of variable based on value passed to it. Compiler don't need a variable to have type statically as a necessary requirement.
Example
- Try the following example, where variables have been declared without any type, and have been defined and initialized inside the main function. Notice, in case of type inference, we've initialized the variable y with := operator where as x is initilized using = operator.
Output :
Mixed variable declaration
- Variables of different types can be declared at a shot as below,