rodriggj / Go

0 stars 0 forks source link

1.4 When to use a short declaration #4

Open rodriggj opened 2 years ago

rodriggj commented 2 years ago

Use a Variable Declaration When ...

  1. If you don't know the initial value of the variable use a Variable Declaration. Example, if you were setting up the initial value of a game that keeps score:

    score := 0       //Don't do this
    var score int    //Instead do this. The initial value will be set to zero by Go by default
  2. Use the Variable Declaration when you need a package scoped declaration.

package main

import ("fmt", )

    version:= 0          // Don't do this
    var version string   // Do this instead

func main(){
    var score int
}
  1. Use a Variable Declaration when you want to group variables together for greater readability. For example if you were modeling a video player. You may have a variable for the video description which is a string. But you may also want to display the duration & the state of the video (current, old, updated, etc). In this case all these variables are related and can be grouped for readability purposes.
package main
import("fmt")

func main() {
    var(
         video string

        duration int
        current string
} 
rodriggj commented 2 years ago

Use a Short Declaration

  1. Short declarations are MOST COMMONLY used. So if none of the reasons above apply, use the short declaration syntax.

  2. If the value of the variable is known then use a short declaration.

    
    package main
    import ("fmt") 

func main() { var width, height = 100, 50 //DONT width, height := 100, 50. //Instead do this }



3. Use `short declaration` for `re-assignment` of variable values. Suppose you have a variable that changes in width or color. 
```go
package main
import("fmt")

func main() {
   width, height : = 100, 50

   //re-assignment of width & adding color ---> DON"T DO THIS
   //width = 50 
   //color := "red"

   //Instead do this 
   width, color := 50, "red"
}