1. Variable Declaration
Variable declaration refers to informing the compiler about the type and name of a variable without allocating memory or initializing it. In Go, variable declaration is typically done using the var
keyword.
1var x int
In this example, x
is declared as a variable of type int
, but at this point, x
is not assigned any initial value. Go will allocate memory for x
and initialize it to the zero value of the int
type (i.e., 0
).
2. Variable Definition
Variable definition refers to declaring a variable while simultaneously allocating memory and assigning it an initial value. In Go, variable definition can be done using the var
keyword or the short variable declaration :=
.
1var x int = 10 // x is declared as a variable of type int and initialized to 10
2x := 10 // x is declared and initialized to 10, and Go automatically infers the type of x as int
3. Summary of Differences
- Variable Declaration: Only declares the type and name of the variable without assigning an initial value. The variable is initialized to the zero value of its type.
- Variable Definition: Declares the type and name of the variable and assigns it an initial value. The variable is initialized to the specified value.
Feature | C Language | Go Language |
---|---|---|
Declaration vs Definition | Strict separation of declaration and definition (extern vs direct definition) | Declaration and definition are usually combined |
Variable Initialization | No initialization during declaration, can initialize during definition | Can skip initialization during declaration (zero value), must initialize during definition |
Type Inference | No support for type inference | Supports type inference (using := ) |
Global Variables | Use extern to declare global variables | Directly use var to declare global variables |
Zero Initialization | Uninitialized global variables are zero, local variables are undefined | All uninitialized variables are zero values |
ogImage: https://image.coldcoding.top/file/AgACAgQAAyEGAASUgNIDAAOdZ-LLW2SY1yk2VuSGbtbqq3iEFT4AAgPGMRuknBlTlzRoYu-UvNoBAAMCAAN3AAM2BA.jpg |