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.
FeatureC LanguageGo Language
Declaration vs DefinitionStrict separation of declaration and definition (extern vs direct definition)Declaration and definition are usually combined
Variable InitializationNo initialization during declaration, can initialize during definitionCan skip initialization during declaration (zero value), must initialize during definition
Type InferenceNo support for type inferenceSupports type inference (using :=)
Global VariablesUse extern to declare global variablesDirectly use var to declare global variables
Zero InitializationUninitialized global variables are zero, local variables are undefinedAll uninitialized variables are zero values
ogImage: https://image.coldcoding.top/file/AgACAgQAAyEGAASUgNIDAAOdZ-LLW2SY1yk2VuSGbtbqq3iEFT4AAgPGMRuknBlTlzRoYu-UvNoBAAMCAAN3AAM2BA.jpg