Standard Variable Declaration and Assignment
Variables can be declared first and assigned values later. In the example below, we declare a variable and then assign it a value:Type Safety
Go’s strong typing system prevents assigning values of an incorrect data type. Consider the example below:Always ensure that the value you assign matches the declared variable type. This prevents compile-time errors and maintains the integrity of your code.
Shorthand Variable Declaration
Go offers a shorthand declaration method that combines declaration and assignment into one concise statement. The compiler automatically infers the variable’s type based on the assigned value.Declaring Multiple Variables of the Same Type
You can declare and assign multiple variables of the same type in a single line. For example:Declaring Variables with Different Types
When working with variables of different types, you can use a multi-line declaration format enclosed in parentheses, as shown below:"foo" and 5.
Short Variable Declaration Using := Operator
The shorthand declaration using the:= operator is a quick and efficient way to declare and initialize a variable. For example:
s is automatically inferred as a string because of the assigned literal "Hello World".
Reassigning Variables
Variables declared with shorthand notation can be reassigned new values of the same type. Take the following example:name was inferred as a string during its initial declaration, it can only be reassigned a string value. Attempting to assign a different type will result in a compile-time error:
Reassign variables only with values of the same type. Mixing data types will lead to compile-time errors due to Go’s strict type safety.
That concludes our lesson on declaring variables in Go. We hope you now have a clearer understanding of variable declaration, assignment, and the importance of type safety in Go programming. For more information on Go and programming best practices, consider exploring Go by Example and the official Go documentation.