Cette page n'est pas encore disponible en français, sa traduction est en cours. Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.
Metadata
ID:go-best-practices/merge-declaration-assignment
Language: Go
Severity: Info
Category: Best Practices
Description
In Go, it is recommended to avoid using separate variable declaration and assignment statements and instead prefer initializing variables directly in the declaration.
Here are a few reasons why:
Simplicity and readability: Initializing a variable in the declaration with var x uint = 1 provides a clear and concise way to express the intent of assigning an initial value to the variable. It reduces unnecessary lines of code, making the code more readable and easier to understand.
Avoiding empty initial values: If you declare a variable with var x uint and then assign it a value of 1 separately, it might initially have an undesired default value (in this case, 0) before you assign the actual desired value. By initializing the variable directly in the declaration, you ensure it starts with the desired initial value.
Encouraging good practice: Initializing variables in the declaration is a recommended coding practice in Go. It follows the principle of declaring variables closer to their usage, promotes legible code, and is widely accepted in the Go community.
Therefore, it is preferable to use var x uint = 1 rather than declaring the variable on one line and assigning it on another. This approach improves code clarity, reduces unnecessary lines, and ensures variables start with the desired initial value.