Reading notes Series ==> the "the" to Go 3

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

4.4 Variables

4.4.1 Introduction

The general form of declaring a variable is to use the var keyword: var identifier type .

It is important to note that Go differs from many programming languages in that it places the type of the variable after the name of the variable when declaring the variable.

Why does go choose to do this?
First, it is intended to avoid the ambiguous form of a declaration like in C, for example: int* a, b; . In this example, only a is a pointer and B is not. If you want both of these variables to be pointers, you need to write them separately (you can find more discussion on this topic in the Go Language Declaration syntax page).

In Go, it is possible and easy to declare them as pointer types:

var a, b *int

Second, this syntax can be read from left to right, making the code easier to understand.

Example:

var a intvar b boolvar str string

You can also change it into this form:

var (a intb boolstr string)

This factorization keyword is commonly used to declare global variables.

When a variable is declared, the system automatically assigns it a value of 0 for the type: int is 0,float to 0.0,bool and false,string is an empty string, and the pointer is nil.

Remember, all memory is initialized in Go.

The naming rules for variables follow the camel nomenclature, which is the first lowercase word, capitalized on the first letter of each new word, for example: numShips and startDate .

But if your global variable wants to be used by an external package, you need to capitalize the first letter of the first word (Section 4.2: Visibility rules).

A variable (constant, type, or function) has a certain scope in the program, called a scope.

If a variable is declared outside the body of a function, it is considered to be a global variable that can be used throughout the package or even an external package (after it is exported), regardless of which source file you declare in or in which source file it is called.

Variables declared in the body of a function are called local variables , their scope is only within the function body, and the parameters and return value variables are local variables.

In the 5th chapter, we will learn about the control structures like if and for, and the scope of the variables declared in these structures is only within the corresponding code block. In general, the scope of a local variable can be judged by a block of code (the part enclosed in curly braces).

Although the identifier of a variable must be unique, you can use a variable of the same name in the inner block of code in a block of code, and the external variable with the same names will be temporarily hidden (the external variable with the same name that is hidden after the execution of the inner code block will appear again, and the internal variable of the name is freed). Any of your operations will only affect local variables of the inner code block.

var aThis syntax is incorrect because the compiler does not have any basis on which to infer the type automatically.
The type of the variable can also be automatically inferred at run time, for example:

var (HOME = os.Getenv("HOME")USER = os.Getenv("USER")GOROOT = os.Getenv("GOROOT"))

This notation is primarily used to declare global variables at the package level, and when you declare local variables in the body of a function, you should use the short declaration syntax := , for example:

a := 1

4.4.2 value types and reference types

All basic types, such as int, float, bool, and string, are value types that use variables of these types to point directly to a value that exists in memory:

In addition, these composite types, like arrays (7th) and Structs (chapter 10th), are also value types.

When you use the equal sign to assign the value = of one variable to another variable, such as: j = i , the value of I is actually copied in memory:

You can get the memory address of the variable I (section 4.9) by &i, for example: 0xf840000040 (each address may be different). The value of a variable of value type is stored in the stack.

The memory address will vary depending on the machine, and even the same program will have different memory addresses when executed on different machines. Because each machine may have different memory layouts, and the location allocation may be different.

More complex data often requires multiple words, which are typically saved using reference types.

A variable of reference type R1 stores the memory address (number) where the value of R1 resides, or where the first word in the memory address resides.

This memory address is called a pointer (which you can clearly see in section 4.9), and the pointer is actually in a different word.

A pointer to the same reference type can be multiple words in a contiguous memory address (the memory layout is contiguous), which is the most computationally efficient form of storage, or it can be scattered in memory, each of which indicates the memory address where the next word resides.

When an assignment statement is used r2 = r1 , only the reference (address) is copied.

If the value of R1 is changed, then all references to the value will point to the modified content, and in this case, R2 will be affected.

In the Go language, pointers (section 4.9) are reference types, and other reference types include slices (7th), maps (chapter 8th), and Channel (13th). The referenced variables are stored in the heap for garbage collection and have a larger memory space than the stack.

4.4.4 short form, using: = Assignment operator

We know that it is possible to omit the type of the variable at the time of initialization of the variable and be automatically inferred by the system, and it is somewhat superfluous to write the keyword on the last declaration statement of the Example 4.4.1 var , so we can abbreviate them to a := 50 or b := false .

The types of A and B (int and bool) are automatically inferred by the compiler.

But global variables are allowed to be declared but not used.

The other short forms are:

Multiple variables of the same type can be declared on the same line, such as:

var a, b, c int   //声明

(This is an important reason to write the type behind the identifier)

A variable can be assigned on the same line, such as:

a, b, c = 5, 7, "abc"  //赋值

The above line assumes that variables a, B, and C are already declared, otherwise this should be used:

a, b, c := 5, 7, "abc"  //(隐式)声明 + 赋值

The values on the right are assigned to the left variable in the same order, so the value of a is, the value of 5 B is 7 , the value of C is "abc" .

This is called parallel or simultaneous assignment.

If you want to swap the values of two variables, you can simply use them a, b = b, a .

(In the Go language, this eliminates the need to use the Swap function)

Blank identifiers are _ also used to discard values, as values are 5 discarded in: _, b = 5, 7 .

_is actually a write-only variable, you can't get its value. This is done because you have to use all the declared variables in the Go language, but sometimes you don't need to use all the return values from a function.

Parallel assignments are also used when a function returns multiple return values, such as here and the val error err is obtained by calling the Func1 function at the same time: val, err = Func1(var1) .

4.4.5 init function

Variables can be initialized in the INIT function, in addition to being initialized in the global declaration. This is a very special kind of function that cannot be called artificially, but is executed automatically after each package is initialized, and the execution priority is higher than the main function.

Each of the source files can contain and contain only one init function. Initialization is always performed as a single thread and is performed in the order of the package dependencies.

One possible use is to verify or repair the data before starting the program to ensure the correctness of the state of the program.

Example 4.6 init.go:

package transimport "math"var Pi float64func init() {   Pi = 4 * math.Atan(1) // init() function computes Pi}

The initial value of the variable Pi is computed in its init function.

The example 4.7 user_init.go imports the package trans (in the same path) and uses the variable Pi:

package mainimport (   "fmt"   "./trans")var twoPi = 2 * trans.Pifunc main() {   fmt.Printf("2*Pi = %g\n", twoPi) // 2*Pi = 6.283185307179586}

The init function is also often used to invoke the goroutine of the background execution before a program starts, as in the following example backend() :

func init() {   // setup preparations   go backend()}

Practice inferring the output of the following programs, explaining your answers, and then compiling and executing them.

Practice 4.1 local_scope.go:

package mainvar a = "G"func main() {   n()   m()   n()}func n() { print(a) }func m() {   a := "O"   print(a)}

Practice 4.2 Global_scope.go:

package mainvar a = "G"func main() {   n()   m()   n()}func n() {   print(a)}func m() {   a = "O"   print(a)}

Practice 4.3 function_calls_function.go

package mainvar a stringfunc main() {   a = "G"   print(a)   f1()}func f1() {   a := "O"   print(a)   f2()}func f2() {   print(a)}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.