"Go get Started Tutorial 2" Built-in basic type (Boolean, numeric, string, error type), grouping, Iota enumeration, array (numeric), slice (slice), map (dictionary), make/new operation, 0 value

Source: Internet
Author: User

In this section we will show you how to define variables, constants, go built-in types, and some techniques in go programming.

Defining variables

There are several ways to define variables in the go language.

Using the var keyword is the basic way to define variables for go, unlike the C language, where go puts the variable type behind the variable name:

Define a variable named "VariableName" with the type "types"
var variableName type

Define multiple variables

Defines three types that are "type" variables
var vname1, vname2, Vname3 type

Defining variables and initializing values

The variable that initializes "VariableName" is "value", and the type is "type"
var variableName type = value

Simultaneous initialization of multiple variables

/*
Defines three types that are "type" variables and are initialized to the corresponding values respectively
Vname1 for V1,vname2 to V2,vname3 for v3
*/
var vname1, vname2, Vname3 type= v1, v2, v3

Do you think the definition above is a bit cumbersome? It doesn't matter, because the Go language designer has found that there is a way to make it easier. We can ignore the type declaration directly, then the above code becomes this:

/*
Define three variables that are initialized to their respective values
Vname1 for V1,vname2 to V2,vname3 for v3
Then go will help you initialize them based on the type of their corresponding values.
*/
var vname1, vname2, Vname3 = v1, v2, v3

Do you think the above is still a little cumbersome? Well, I think so, too. Let's continue to simplify:

/*
Define three variables that are initialized to their respective values
Vname1 for V1,vname2 to V2,vname3 for v3
The compiler automatically infers the corresponding type based on the initialized value.
*/
Vname1, vname2, Vname3: = V1, v2, v3

Does it look very concise now? : = This symbol directly replaces Var and type, which is called a short declaration. However, it has a limitation that it can only be used inside a function, and it cannot be compiled by using outside of the function, so it is generally used to define global variables in var mode.

_ (underscore) is a special variable name, and any value given to it will be discarded. In this example, we give a value of 35 to B and discard 34 at the same time:

_, B: = 34, 35

Go to the declared but unused variables will be in the compilation phase error, such as the following code will produce an error: declared I but not used.

Package Main

Func Main () {
var i int
}

Constant

The so-called constant, which is the value determined at the time of the program's compilation, cannot be changed by the program at runtime. In Go programs, constants can be defined as numbers, Boolean values, or string types.

Its syntax is as follows:

Const CONSTANTNAME = value
You can also explicitly specify the type of the constant, if desired:
Const Pi float32 = 3.1415926

Here are some examples of constant declarations:

Const PI = 3.1415926
Const I = 10000
Const MAXTHREAD = 10
Const prefix = "Astaxie_"

Go constants and general programming language is different, you can specify a considerable number of decimal digits (such as 200-bit), if assigned to float32 automatically shortened to 32bit, assigned to float64 automatically shortened to 64bit, details reference link

Built-in base type Boolean

In Go, the Boolean value is bool, the value is true or FALSE, and the default is False.

Sample code
var isActive bool//global variable declaration
var enabled, disabled = True, false//Ignore type declaration
Func Test () {
var available bool//general Declaration
Valid: = FALSE//Short declaration
Available = TRUE//assignment operation
}

Numeric type

An integer type has unsigned and signed two types. Go supports both int and uint, both types are the same length, but the exact length depends on the implementation of the different compilers. Go also has a direct definition of the type of the number of digits: Rune, Int8, Int16, Int32, Int64 and Byte, Uint8, UInt16, UInt32, UInt64. Where Rune is Int32 's nickname, Byte is Uint8 's nickname.

It is important to note that these types of variables are not allowed to assign values or operations to each other, or will cause the compiler to error when compiling.

The following code generates an error: invalid OPERATION:A + b (Mismatched types int8 and Int32)

var a int8

var b int32

C: =a + b

In addition, int is not interoperable with int32, although the length of int is three bit.

There are two types of floating-point numbers float32 and float64 (no float type), and the default is float64.

Is that all? No! Go also supports complex numbers. Its default type is complex128 (64-bit real number + 64-bit imaginary number). If smaller, there are also complex64 (32-bit real number + 32-bit imaginary numbers). The plural form is re + IMi, where re is the real part, IM is the imaginary part, and the last I is the imaginary unit. Here is an example of using a complex number:

var c complex64 = 5+5i
Output: (5+5i)
Fmt. Printf ("Value is:%v", c)

String

As we said in the previous section, the strings in Go are encoded using the UTF-8 character set. The string is defined in a pair of double quotation marks ("") or an inverse quotation mark ("'), which is of type string.

Sample code
var Frenchhello string//general method of declaring a variable as a string
var emptystring string = ""//declares a string variable initialized to an empty string
Func Test () {
No, yes, maybe: = "no", "yes", "maybe"//short declaration, and declaration of multiple variables
Japanesehello: = "Konichiwa"//Ibid.
Frenchhello = "Bonjour"//general Assignment
}

In go, the string is immutable, for example, the following code compiles with an error: cannot assign to s[0]

var s string = "Hello"
S[0] = ' C '

But what if you really want to change it? The following code can be implemented:

s: = "Hello"
c: = []byte (s)//convert string s to []byte type]
C[0] = ' C '
S2: = string (c)//To convert back to string type
Fmt. Printf ("%s\n", S2)

You can use the + operator to connect two strings in go:

s: = "Hello,"
M: = "World"
A: = s + M
Fmt. Printf ("%s\n", a)

The modified string can also be written as:

s: = "Hello"
s = "C" + s[1:]//string cannot be changed, but can be sliced
Fmt. Printf ("%s\n", s)

What if I want to declare a multi-line string? Can be declared by ':

M: = ' Hello '
World '

' Enclose the string as a raw string, that is, the form of the string in the code is the form of printing, it has no character escapes, and the newline is output as is. For example, in this example, the output is:

Hello
World

Type of error

The go built-in has an error type that is specifically designed to handle errors, and the Go package also has a packet errors to handle the error:

ERR: = errors. New ("Emit macho dwarf:elf header corrupted")
If err! = Nil {
Fmt. Print (ERR)
}

Storage for GO data underlying

The following figure comes from an article in Russ Cox blog that introduces the go data structure, and you can see that the underlying type is assigned a piece of memory and then stored with the corresponding value.

Figure 2.1 The Go data format storage

Some tips for grouping statements

In the go language, when declaring multiple constants, variables, or importing multiple packages, you can declare them in a grouped way.

For example, the following code:

Import "FMT"
Import "OS"

Const I = 100
Const PI = 3.1415
Const prefix = "Go_"

var i int
var pi float32
var prefix string

Can be grouped into the following form:

Import
"FMT"
"OS"
)

Const
i = 100
PI = 3.1415
prefix = "Go_"
)

var
I int
Pi float32
Prefix string
)

Iota Enumeration

Go has a keyword iota, which is used when declaring an enum, and its default starting value is 0,const each additional line plus 1:

Const
x = iota//x = = 0
y = iota//y = = 1
z = iota//z = = 2
When a w//constant declares an ellipsis, the default is the same literal as the previous value. Here implicitly says W = iota, so w = = 3. In fact, the above Y and Z can also not "= Iota"
)

Const V = iota//each time a const keyword is encountered, iota is reset, at which point v = = 0

Const (
E, f, g = iota, iota, iota//e=0,f=0,g=0 iota same row value
)

Const (
A = Iota a=0
b = "B"
c = Iota//c=2
D,e,f = Iota,iota,iota//d=3,e=3,f=3
G//g = 4
)

Unless explicitly set to another value or iota, the first constant of each const group is set to its 0 value by default, and the second and subsequent constants are set by default to the value of the constant preceding it, and if the value of the preceding constant is iota, it is also set to iota.

Some rules of Go programming

Go is so concise because it has some default behavior:

    • The variable at the beginning of the capital letter is exportable, which is the public variable that the other package can read, and the lowercase letter begins with a non-exportable, private variable.
    • A function that starts with a capital letter is the same as a public function with a common keyword in class, and a private function that starts with a secret keyword.
Array, slice, Maparray

An array is a pattern that is defined as follows:

var arr [N]type

in [N]type, n represents the length of the array, and type represents the types of the stored elements. Operations of an array are similar to other languages, and are read or assigned by []:

var arr [10]int//declares an array of type int
ARR[0] = 42//array subscript is starting from 0
ARR[1] = 13//Assignment operation
Fmt. Printf ("The first element is%d\n", arr[0])//Get data, return 42
Fmt. Printf ("The last element is%d\n", arr[9])//Returns the final element that is not assigned, returns 0 by default

Because length is also part of the array type, [3]int and [4]int are different types, and arrays cannot change length.] The assignment between arrays is the assignment of a value, that is, when an array is passed into a function as a parameter, it is actually a copy of the array, not its pointer. If you want to use pointers, then you need to use the slice type described later.

An array can use another: = To declare

A: = [3]int{1, 2, 3}//declares an int array of length 3

B: = [10]int{1, 2, 3}//declares an int array of length 10, where the first three elements are initialized to 1, 2, 3, others default to 0

c: = [...] Int{4, 5, 6}//Can omit length and adopt ' ... ' way, go will automatically calculate the length based on the number of elements

Perhaps you would say, I think the array inside the value or array, can it be implemented? Of course, go supports nested arrays, or multidimensional arrays. For example, the following code declares a two-dimensional array:

Declares a two-dimensional array with two arrays as elements, with 4 elements of type int in each array
Doublearray: = [2][4]int{[4]int{1, 2, 3, 4}, [4]int{5, 6, 7, 8}}

The above declaration can be simplified, ignoring the internal type directly
Easyarray: = [2][4]int{{1, 2, 3, 4}, {5, 6, 7, 8}}

The allocation of the array is as follows:

Figure 2.2 Mapping relationships of multi-dimensional arrays

Slice

In many scenarios, arrays do not meet our needs. When we initially define an array, we do not know how large an array is needed, so we need a "dynamic array". In go, this data structure is called slice.

Slice is not a real dynamic array, but a reference type. Slice always points to an underlying Array,slice declaration can also be like an array, just without the need for length.

As with the declaration array, only the length is missing
var Fslice []int

Next we can declare a slice and initialize the data as follows:

Slice: = []byte {' A ', ' B ', ' C ', ' d '}

Slice can be declared again from an array or an already existing slice. Slice is obtained by array[i:j], where I is the beginning of the array, J is the end position, but does not contain array[j], and its length is j-i.

Declares an array containing 10 elements of type Byte
var ar = [10]byte {' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' J '}

Declares two slice that contain a byte
var a, b []byte

A points to the 3rd element of the array, and ends with the fifth Element,
A = Ar[2:5]
Now a contains elements: ar[2], ar[3] and ar[4]

B is another slice of the array ar
b = Ar[3:5]
The elements of B are: ar[3] and Ar[4]

Note the difference between the slice and the declaration: When declaring an array, the length of the array is indicated in square brackets or used ... The length is automatically calculated, and when the slice is declared, there are no characters in the square brackets.

Their data structures are shown below

Figure 2.3 Diagram of slice and array

Slice has some simple operations

    • The default starting position for slice is 0,ar[:n] equivalent to ar[0:n]
    • The second sequence of slice is the length of the array by default, Ar[n:] equivalent to Ar[n:len (AR)]
    • If you get slice directly from an array, you can ar[:] because the default first sequence is 0, the second is the length of the array, which is equivalent to Ar[0:len (AR)]

The following example shows more about slice:

Declares an array
var array = [10]byte{' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' J '}
Declaration of two Slice
var aslice, Bslice []byte

Demonstrate some simple operations
Aslice = Array[:3]//equivalent to Aslice = Array[0:3] Aslice contains element: A,b,c
Aslice = array[5:]//equivalent to Aslice = Array[5:10] Aslice contains element: F,g,h,i,j
Aslice = array[:]//equivalent to Aslice = Array[0:10] So aslice contains all the elements

Get Slice from slice
Aslice = Array[3:7]//Aslice contains element: d,e,f,g,len=4,cap=7
Bslice = Aslice[1:3]//Bslice contains aslice[1], aslice[2] that is, contains: e,f
Bslice = Aslice[:3]//Bslice contains aslice[0], aslice[1], aslice[2] that is, contains: d,e,f
Bslice = Aslice[0:5]//slice for slice can be extended within the CAP range, at which time Bslice contains: d,e,f,g,h
Bslice = aslice[:]//Bslice contains all elements of Aslice: D,e,f,g

Slice is a reference type, so when the reference changes the value of the element, all other references change that value, such as the Aslice and Bslice above, and if the value of the element in the Aslice is modified, the corresponding value of the bslice is changed.

From the concept above, slice is like a struct, which contains three elements:

    • A pointer to the starting position of the slice specified in the array
    • length, i.e. the length of the slice
    • Maximum length, which is the length of the slice start position to the last position of the array

      Array_a: = [10]byte{' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' J '}
      Slice_a: = Array_a[2:5]

The actual storage structure of the above code is shown

Figure 2.4 Slice the corresponding array information

There are several useful built-in functions for slice:

    • Len gets the length of the slice
    • Cap gets the maximum capacity of the slice
    • Append appends one or more elements to the slice and returns a slice of the same type as slice
    • The copy function copy copies elements from the src of the source slice to the target DST, and returns the number of copied elements

Note: The Append function alters the contents of the array referenced by slice, thus affecting other slice that refer to the same array. However, when there is no space left in the slice (i.e. (cap-len) = = 0), the new array space is dynamically allocated. The returned slice array pointer will point to this space, and the contents of the original array will remain unchanged, while other slice referencing this array are unaffected.

Starting from Go1.2 Slice supports three parameter slice, which we have used in this way to get a slice on slice or array basis.

var array [10]int
Slice: = Array[2:4]

In this example, the capacity of slice is 8, and the new version can specify this capacity

Slice = Array[2:4:7]

The capacity of the above is 7-2, or 5. The resulting new slice will not be able to access the last three elements.

If slice is in this form array[:i:j], that is, the first argument is empty, the default value is 0.

Map

Map is the concept of a dictionary in Python, which is formatted as Map[keytype]valuetype

We look at the following code, the map reading and setting is similar to slice, through the key to operate, only the slice index can only be ' int ' type, and map many more types, can be an int, can be a string and all the types that fully define the = = and! = operation.

Declares that a key is a string, and the value is a dictionary of int, and that declaration needs to be initialized with make before use.
var numbers map[string]int
Another way to declare a map
Numbers: = Make (Map[string]int)
numbers["one"] = 1//Assignment
Numbers["ten"] = 10//Assignment
Numbers["three"] = 3

Fmt. Println ("Third number is:", numbers["three"])//Read data
Print out such as: The third number is: 3

This map is like the table we normally see, the left column is key, the right column is the value

Points to note when using the map process:

    • Map is unordered, each printed map will be different, it can not be obtained through the index, but must be obtained through key
    • The length of the map is not fixed, that is, like slice, is also a reference type
    • The built-in Len function also applies to the map, returning the number of keys the map has
    • The value of map can be easily modified by numbers["One"]=11 can easily change the key to one of the dictionary value to 11
    • Map is different from other basic types, it is not thread-safe, and the mutex lock mechanism must be used when multiple go-routine are accessed

The initialization of the map can be initialized by Key:val, and the map has a built-in way to determine if a key exists.

Delete the elements of the map via delete:

Initialize a dictionary
Rating: = map[string]float32{"C": 5, "Go": 4.5, "Python": 4.5, "C + +": 2}
Map has two return values, the second return value, if no key exists, then OK is false, if there is OK is true
Csharprating, OK: = rating["C #"]
If OK {
Fmt. Println ("C # is in the map and it rating is", csharprating)
} else {
Fmt. Println ("We have no rating associated with C # in the map")
}

Delete (rating, "C")//remove element with key C

As mentioned above, map is also a reference type, and if two maps point to one level at a time, then one change and the other changes accordingly:

M: = Make (map[string]string)
m["Hello"] = "Bonjour"
M1: = m
The value of m1["Hello"] = "Salut"//Now m["Hello"] is already Salut

Make, new operation

Make is used for memory allocations of built-in types (map, slice, and channel). New is used for various types of memory allocations.

The built-in function new is essentially the same as the function of the same name in other languages: new (T) allocates 0 of the memory space of the T type populated by the value, and returns its address, which is a value of type *t. In the terms of go, it returns a pointer to the 0 value of the newly assigned type T. One thing is very important:

New returns a pointer.

The built-in function make (T, args) has a different function than new (t), making can only create slice, map, and channel, and returns a T type with an initial value (not 0) instead of *t. Essentially, the reason that these three types are different is that references to data structures must be initialized before they are used. For example, a slice is a three-item descriptor that contains pointers, lengths, and capacities to the data (internal array), and slice is nil until those items are initialized. For slice, map, and channel, make initializes the internal data structure and populates the appropriate values.

Make returns the initialized (not 0) value.

The diagram below explains in detail the difference between new and make.

Figure 2.5 make and new correspond to the underlying memory allocations

0 value

With respect to "0 value", it is not a null value, but rather a default value of "before the variable is filled", typically 0. This is a list of the "0 values" for some types.

int 0
int8 0
Int32 0
Int64 0
UINT 0x0
The actual type of Rune 0//rune is int32
The actual type of byte 0x0//byte is uint8
float32 0//Length 4 byte
Float64 0//Length 8 byte
BOOL False
String ""

From

Https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/02.2.md

"Go get Started Tutorial 2" Built-in basic type (Boolean, numeric, string, error type), grouping, Iota enumeration, array (numeric), slice (slice), map (dictionary), make/new operation, 0 value

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.