Go variables in language learning


01 naming rules

The naming rule in go is that the name starts with a letter or an underline, followed by any number of characters, numbers and underscores. The characters are case sensitive and the name itself has no length limit. However, the programming style of go tends to use short names, especially local variables. There are 25 keywords in go, which cannot be used for naming.

Go language 25 Keywords:

break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var

02 declaration variable

  • The general form of declaring variables
var name type = expression

Use the VaR keyword, followed by the name, type, and expression of the variable.

  • The omitted form of declared variables
var totalScore int
var totalScore2 = 678

Omitting formal declaration variables, types and expressions can omit one of them, but not both. Omit an expression whose initial value is the zero value of the type, omit the type, and its initialization expression determines the type of the variable.

  • Declare variable list
var a, b, c int
var d, e, f int = 1, 2, 3
var g, h, i = 3.14, "hello", true

Declare variable list, omit type, determine the type of variable by initialization expression, and allow multiple variables of different types to be declared.

  • Call the formal declaration variable with return value function
var myname = name("lucy")
func name(name string) string {
  var str string = "My name is " + name
  return str

03 declare short variable

In functions, short variable declarations are used to declare and initialize local variables.

Declare a local variable of type integer:

totalScore := 123

Declare a short variable list:

x, y := 1, 2

Note: short variable declaration, at least one new variable must be declared on the left.

04 pointer

The value of the pointer is the address of a variable. A pointer represents the location where the value of a variable is stored. The pointer can read and update the value of a variable without knowing its name.

var x int

Declare an integer variable x and & X get a pointer to variable x whose type is integer pointer type (* int)

  z := 3
  p := &z
  fmt.Printf("z=%d\n", z)
  fmt.Printf("p=%p\n", p)
  *p = 4
  fmt.Printf("z=%d\n", z)
  fmt.Printf("p=%p\n", p)

P is a pointer to Z, is the address of Z, and its type is an integer pointer type(int),P is the value of the variable Z, which is an alias of the variable Z, which can be read and updated.

The zero value of pointer type is nil, and the pointer is comparable. Two pointers are equal only when they point to the same variable or both are nil.

Go Language Basics

Go variables in language learning