Go - Declare Variables


Declaration
  1. Declare package
  2. Declare import
  3. var/const/func/type can be declared in any order

Variables
Declare variables with the same type and different types
Declare variables by method return multiple values
Short Variable Declaration
Use pattern "variables := expression" can declare variables.
package main
import (
       "fmt"
)
func main() {
       i, j := 1, 2
       fmt.Printf("%d, %d", i, j)
}
Short variable declaration expression can return multiple values
package main
import (
       "fmt"
)
func main() {
       q, k := multiReturn()
       fmt.Printf("%d, %d", q, k)
}
func multiReturn() (int, int) {
       return 3, 4
}
Must declare at least one new variable!
package main
import (
       "fmt"
)

// Declare new variable "q"
func main() {
       i, j := 1, 2
       j, q := i, j 
       fmt.Printf("i=%d,j=%d,q=%d", i, j, q)
}
Otherwise it will compile error



沒有留言:

張貼留言

caffeinate – make your Mac awake

When running long tests on macOS, the machine may go to sleep if you don’t touch it. There’s a built-in command that keeps it awake. ...