Go Variables and Constants

Variable Declaration

Standard Declaration

var variableName variableType

Variable declarations begin with the keyword var, followed by the variable type after the variable name. Unlike C/C++/Java, semicolons are not required at the end of the line.

var name string
var age int
var isOk bool

Batch Declaration: Declaring variables one by one with the var keyword can be cumbersome. Go supports batch variable declaration, making it more concise:

var (
      name string
      age int
      isOk bool
)

Variable Initialization: When declaring variables in Go, the corresponding memory regions are automatically initialized. Each variable is initialized to its type's default value: integers and floating-point variables default to 0, string variables default to an empty string, boolean variables default to false, and slices, functions, and pointer variables default to nil.

  var variableName variableType = expression
e.g.:
  var name string = "synfun.com"
  var age int = 18
or
  var name, age = "synfun.com", 18

Type Inference: Sometimes we might omit the variable's type (for brevity?). The Go compiler infers the variable's type based on its value, thereby completing the initialization.

var name = "synfun.com"
var age = 18

:= Declaring and Initializing Local Variables: Within a function, you can use the more concise := syntax to declare and initialize local variables. Note that := cannot be used outside of functions.

package main
import (
  "fmt"
)
var name = "synfun.com" //global variable name
func main() {
  age := 18 //local variable age
  fmt.Println(name, age)
}

Constant Declaration

In contrast to variables, constants are immutable values, often used to define values that will not change during program execution. Constants must be assigned a value during declaration.

  const constantName = expression
e.g.:
  const domain = "synfun.com"
  const register = 2013
or
  const (
      domain = "synfun.com"
      register = 2013
  )

 

Take a break

๐Ÿ‘‰๐Ÿ‘‰๐Ÿ‘‰ ใ€BTTH Year EP98ใ€‘Heaven Mountain Blood Pool story opened. Feng Qing'er is comming...