Go program structure

  • A program written in Go corresponds to one or more source files with a. Go file suffix
  • Each source file starts with a package declaration stating which package the source file belongs to
  • The package declaration statement is followed by the import statement that imports the other packages that depend on
  • This is followed by package-level declarations of types, variables, constants, and functions whose names are accessible in each source file corresponding to the entire package
  • Finally, there are the individual local declarations, whose names can only be accessed within a narrow range of functions.

The statement

The Go language has four main types of declarations:

  • Var: variable
  • Const: constant
  • Type: type
  • Func: function entity
package main

import "fmt"

// Package level declaration
const boilingF = 212.0

func main(a) {
    // Local declaration
    var f = boilingF
    var c = (f - 32) * 5 / 9
    fmt.Printf("boiling point = %g°F or %g°C\n", f, c)
    // Output:
    // boiling point = 212°F or 100°C
}
Copy the code

variable

The var declaration statement creates a variable of a particular type, appends it to a name, and sets its initial value. The general syntax for variable declarations is as follows:

Var Variable name type = expressionCopy the code

The “type” or “= expression” parts can be omitted.

  • If type information is omitted, the type information of the variable is derived from the initialization expression.
  • If the initialization expression is omitted, the variable is initialized with a zero value.
    • The zero value for a numeric variable is 0
    • Boolean variables have a zero value of false
    • The zero value corresponding to the string type is an empty string
    • The zero value corresponding to an interface or reference type (including slice, pointer, map, chan, and function) is nil
    • An aggregate type such as an array or struct has a zero value for each element or field.
1. Short variable declarations
anim := gif.GIF{LoopCount: nframes}
freq := rand.Float64() * 3.0
t := 0.0

// Declare multiple variables simultaneously
i, j := 0.1
Copy the code
  • The variables to the left of the short variable declaration may not all be newly declared. If there are already declared variables in the same locale, then the short variable declaration statement has only assignment behavior for those already declared variables.
  • At least one new variable must be declared in the short variable declaration statement, or the compilation will fail
Pointer to 2.

The value of a pointer is the address of another variable.

x := 1
p := &x         // &x takes the memory address of x
fmt.Println(*p) / / "1"
*p = 2          // *p p specifies the value of the variable to which the pointer points
fmt.Println(x)  / / "2"
Copy the code
3. The new function

Another way to create a variable is to call the built-in new function. The expression new(T) creates an anonymous variable of type T, initializes it to a zero value of type T, and then returns the address of the variable, returning a pointer of type *T.

p := new(int)   // p, *int, pointing to an anonymous int variable
fmt.Println(*p) / / "0"
*p = 2          // Set the int anonymous variable to 2
fmt.Println(*p) / / "2"
Copy the code

The new function is a kind of syntactic sugar. There is no difference between creating variables with new and normal variable declaration statements

func newInt(a) *int {
    return new(int)}func newInt(a) *int {
    var dummy int
    return &dummy
}
Copy the code

Now that you’ve learned about variable declarations, you can continue to learn about the life cycle of variables

  • For variables declared at the package level, their lifetime is consistent with that of the entire program.
  • By contrast, the life cycle of local variables is dynamic: each time a declaration statement creates a new variable, the variable is no longer referenced, and then the storage space of the variable may be reclaimed. Both the argument and return variables of a function are local variables

The assignment

x = 1                       // Assign a named variable
*p = true                   // Assign indirectly through a pointer
person.name = "bob"         Struct field assignment
count[x] = count[x] * scale // Array, slice, or map element assignment
Copy the code

Tuple assignment: Tuple assignment is another form of assignment statement that allows the values of multiple variables to be updated simultaneously. Before assignment, all expressions on the right side of the assignment statement are evaluated, and then the values of the corresponding variables on the left are uniformly updated.

x, y = y, x

a[i], a[j] = a[j], a[i]
Copy the code

Assignability: Assignment statements are explicit assignments, but there are many other places in the program where implicit assignments can occur.

  • A function call implicitly assigns the value of the calling argument to the function’s argument variable
  • A return statement implicitly assigns the value of the return operation to the result variable
  • Literals of a compound type also produce assignment behavior.

type

A type declaration statement creates a new type name that has the same underlying structure as an existing type. The newly named type provides a way to separate types of different concepts so that they are incompatible even if their underlying type is the same.

Type Indicates the underlying type of the type nameCopy the code

Type declaration statements generally occur at the package level, so if the first character of a newly created type name is uppercase, it can be used outside the package.

package tempconv

import "fmt"

type Celsius float64    // Celsius temperature
type Fahrenheit float64 // The temperature is Fahrenheit

const (
    AbsoluteZeroC Celsius = 273.15 // Absolute zero
    FreezingC     Celsius = 0       // Freezing point temperature
    BoilingC      Celsius = 100     // Boiling water temperature
)

func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32)}func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9)}Copy the code

For each type T, there is a corresponding conversion operation, T(x), that converts x to T.

  • This transformation operation is allowed only if the underlying base type of the two types is the same
  • Or if they are both pointer types to the same underlying structure, these conversions only change the type and do not affect the value itself.
  • If x is a value that can be assigned to T, then x can certainly be converted to T as well, but this is usually not necessary.

Packages and files

Packages in Go are similar in concept to libraries or modules in other languages and are designed to support modularity, encapsulation, separate compilation, and code reuse. The source code of a package is stored in one or more source files with file name extensions of. Go. Usually, the suffix of the directory path of a package is the import path of the package.

  • Each package corresponds to a separate namespace.

    The Decode function in the Image package is different from the Decode function in the Unicode/UTF16 package. To reference this function externally, you must explicitly access it using image.Decode or UTf16.decode.

  • Packages also allow us to hide internal implementation information by controlling which names are externally visible.

    In the Go language, a simple rule is that a name is exported if it begins with a capital letter