Go Language Learning Notes (2nd)-Type section

Source: Internet
Author: User
Tags bitwise operators constant definition
This is a creation in Article, where the information may have evolved or changed. 2nd Chapter: Sequential Programming
The go language is known as the "Better C language"
1. Variables
1) Declaration of variables The Go language introduces a keyword var, and type information is placed after the variable name
Example: var v1 int
Multiple variable declarations can be put together, for example: VAR (v1 int v2 string)
2) There are 3 ways to initialize variables: var v1 int = Ten var v2 = v3: = 10
The go language introduces new symbols (a combination of colons and equal signs :=), which is used to express variable declaration and initialization at the same time, but if: = the left side of the variable has been declared, and then use this symbol to compile the error
var i int i: = 2//This compilation will error
The specified type is no longer necessary, and the go compiler can deduce from the right value of the initialization expression which type the variable should be declared, which makes the go language look a bit like a dynamic type language (the go language is actually a static type language that is virtually absolute)
3) The assignment process after declaring a variable var v10 int v10 = 123
go provides multiple assignment functionsFor example, exchanging the language of the I and J variables, the previous language needs to introduce an intermediate variable, but go can do this: I, j = j, I
4) Anonymous variables
2. Constants
In the go language, constants refer to values that are known and immutable during compilation. Constants can be numeric types, Boolean types, string types.
The literal constants of the go language are much closer to the constant concept in our natural language and are untyped. As long as the constant is within the range of the corresponding type, it can be used as a constant of that type. For example-12, you can assign values to int, uint, Int32, float32 ... such as
1) constant definition and C, defining constants is also used ConstKey words
If you define a constant without specifying a type, it is, like a literal constant, an untyped constant.


2) predefined constants The Go language pre-defines these constants: true, false and iota Iota are special, can be considered a compiler can be modified by a constant, when each const keyword appears to be reset to 0, and then before the next const appears, each occurrence of iota, The number that it represents will automatically increase by 1.


If the expression for the two Const assignment language is the same, then the latter assignment expression can be omitted


The above two statements are the same
3) Enumeration enumeration refers to a series of related constants, and the go language does not support many other language-supported enum keywords defines a set of constants in the form of a const followed by a pair of parentheses, which is typically used to define enumeration values in the Go language.

In the go language, constants that start with uppercase letters are visible outside the package, numberofdays are private inside the package, and other symbols can be accessed by other packages.
3. Type
The go language has the following underlying types: Boolean type: bool integer: int8, Byte, int16, int, uint, uintptr floating-point type: float32, float64 Complex Type: complex64, complex128 string: Stri ng character type: Rune Fault type: Error
The go language supports the following composite types:
Pointers (pointer), arrays (array), slices (slice), dictionary (map), channel (chan) struct (struct), Interface (interface)
Above these base types go also encapsulates the following types: int, uint, uintptr, and so on. These types are characterized by ease of use, but the user cannot make any assumptions about the length of these types. For regular developers, with int and uint, there is no need to explicitly specify a length type such as int8 to avoid porting difficulties.
1) Boolean type Boolean types cannot accept other types of assignments, and automatic or forced type conversions are not supported.

2) Integral typeInteger is the most basic data type in all programming languages. int and Int32 are considered to be two different types in the go language. The compiler will not help you do the type conversion automatically.

This compilation error can be resolved with coercion type conversion:

Numeric OperationsThe go language supports the following general integer operations: +,-, *,/and% and is the same as in the C language for Shing calculations, e.g.: 5 3//result is 2
comparison OperationThe go language supports several comparison operators: <, = =, >=, <=, and! =
two different types of integers cannot be directly compared, such as the number of int8 types and the number of int cannot be directly compared, but all types of integer variables can be directly compared with literal constants


bit arithmetic most of the bitwise operators in the Go language are similar to the C language, except that they are ~x in the C language and ^x in the Go language .
3) Float typeFloating-point types are used to represent data that contains a decimal point. The go language defines two types of float32, float64, where float32 is equivalent to the float type in C, and float64 is equivalent to the double type of the C languageIf you define floating-point types like this: fvalue2: = 12.0 The type will be automatically set to float64, regardless of whether the number assigned to him is expressed in 32-bit length.


Because floating-point numbers are not an exact representation, it is not feasible to use = = as an integer to determine whether two floating-point numbers are equal, which can lead to unstable results. The alternative is to subtract less than 0.00001 after subtracting the difference
4) StringIn the go language, strings are also a basic type.
the contents of a string can be obtained in a manner similar to an array subscript, the contents of the string cannot be modified after initialization
The use of the printf () function in the go language is the same as the printf () function in the C language runtime.
The go language only supports UTF-8 and Unicode encoding. For other encodings, the Go Language standard library does not have built-in encoding conversion support. Fortunately, however, we can easily package one with CGO based on the Iconv library.
A. String common operations are: string connection, string length, take character

B. String traversal the Go language supports two ways of traversing a string.


When traversing in Unicode characters, the type of each character is Rune, not byte
4. Character TypesSupports two character types in the go language, one is byte, the value of a single byte representing the UTF-8 string, and the other is Rune, which represents a single Unicode character
5. Arrays
Arrays are one of the most commonly used data structures in the go language.
In the go language, the length of an array cannot be changed after it is defined, and the length can be a constant or a constant expression at the time of declaration. The length of the array is a built-in constant for the array type, which can be obtained using the go language's built-in function Len ().
A. Element access uses an array subscript to access the elements in the array, starting with the subscript 0. Len (Array)-1 indicates the subscript of the last element. The go language provides a keyword RangeTo easily traverse the elements in the container. Arrays are also ranges supported by range. Range has two return values, the first return value is an array subscript for the element, and the second return value is the value of the element.
B. Value types in the Go language an array is a value type, and all value type variables produce a copy action when they are assigned and passed as parameters. If you use an array as the parameter type for a function, the parameter will be assigned a data value when the function is called. Therefore, the contents of the incoming array cannot be modified in the body of the function, because only one copy of the incoming array is manipulated inside the function.
The array that is manipulated in modify () is two different instances from the array passed in main (). If you want to manipulate external data structures within a function, you can use array slicing to achieve this goal.
6. Array slicingArray Features: The length of the array cannot be modified after it is defined, the array is a value type, and each pass produces a copy.
The go language also provides array slices (slice) to compensate for the lack of arrays. At first glance, an array slice is like a pointer to an array, and in fact it has its own data structure, not just a pointer. The data structure of an array slice can be abstracted into the following 3 variables:
    • A pointer to the native array
    • number of elements in an array slice
    • array Tiles allocated storage space
From the bottom-level implementation point of view, array slices actually still use arrays to manage elements. Array-based, array slicing adds a series of management functions that can dynamically expand the storage space at any time and can be transferred at will without causing the managed elements to be duplicated.
A. There are two main ways to create array slices to create arrays of tiles-based on arrays and directly created.
The array is created as follows:

For Go language support Myarray[first:last]Such a way to generate an array slice based on an array, and this usage is flexible, such as the following are legal: Myslice = myarray[:] myslice = myarray[:5] Myslice = myarray[5:]
Create directly: It is not always necessary to prepare an array in advance to create an array slice. The built-in function make () provided by the go language can be used to flexibly create array slices. Example:
Of course, there's actually an anonymous array created, but we don't need to worry about it.
B. Element traversal all methods of array elements apply to array slices, such as array slices can also be read and write elements by subscript, with the Len () function to get the number of elements, and support the use of the range keyword to quickly traverse all elements.

C. Array slices can be dynamically added and subtracted elements are more powerful than array slices. Compared with arrays, array slicing has a concept of storage capacity, that is, the number of elements and the allocated space can be two different values. A reasonable setting of the value of the storage capacity can significantly reduce the frequency of memory redistribution and the number of memory blocks inside the array tiles, thus greatly improving program performance.
Assuming you know for sure that the array tiles you are currently creating may require a maximum of 50 elements to be stored, if you set the storage capacity to less than 50, such as 20, then at least one of these actions will occur at the bottom of the element at more than 20 o'clock: reallocate a "big enough" memory, And it is necessary to copy the content from the original memory block to the newly allocated memory block, which has a significant overhead. The word "big enough" is quoted because the system doesn't know how big it is, so it's just a simple guess. For example, expanding the original memory space by twice times, but twice times is not necessarily enough, so the memory redistribution and content replication process mentioned earlier is likely to occur many times, thus significantly reducing the overall performance of the system. But if you know the maximum is 50 and set the storage capacity at the beginning of 50, then there will not be such a very CPU-consuming action, so as to achieve the effect of space exchange time.
Array slices support the go language's built-in cap () function and the Len () function, and the CAP () function returns the amount of space allocated by the array slice, and the Len () function returns the number of elements currently stored in the array slice.


Continue to add elements after the 5 elements that Myslice already contain, you can use the Append () function
The second parameter of the function append () is an indeterminate parameter, we can add several elements to our own needs, or even directly append one array slice to the end of another array slice:

It should be noted that after the second parameter MySlice2 3 points are added, that is, an ellipsis, if there is no such ellipsis, there will be a compilation error, because by the semantics of append (), all parameters from the second parameter are the element to be attached. Because the element type in Myslice is int, it is not feasible to pass MYSLICE2 directly. The ellipsis is equivalent to breaking all the elements contained in the MySlice2 and passing in.
The above call is equivalent to: Myslice = Append (Myslice, 8, 9, 10)
Array slices automatically handle the problem of insufficient storage space. If the appended content is longer than the currently allocated storage space, the array slice is automatically allocated a chunk of memory that is large enough.
D. Creating an array slice array slice based on an array slice can also be created from another array slice. Interestingly, the range of Oldslice elements selected can even exceed the number of elements contained, such as Newslice can be created based on the first 6 elements of Oldslice, although Oldslice contains only 5 elements. As long as the range of this selection does not exceed the Oldslice storage capacity (that is, the value returned by the CAP ()), then the creation process is legal. The part of the newslice that exceeds the Oldslice element will be filled with 0.
E. Content copy array tiles another built-in function copy () that supports the go language is used to copy content from one array slice to another. If you add two array slices that are not the same size, they will be copied by the number of elements in the smaller array.

7. MapIn the go language, using map does not need to introduce any libraries, and it is convenient to use them.

A. Variable declaration var myMap map[string] PersonInfo Mymap is the name of the declared map variable, string is the type of the key, and Personinfo is the type of the value in which it is stored.
B. Create a new map MyMap = make (map[string] PersonInfo) using the Go language built-in function make (), or choose whether to specify the initial storage capability of the map when it is created, such as MyMap = Make (Map[stri NG] PersonInfo, 100)//initial storage capacity of 100
You can also create and initialize map MyMap = map[string] personinfo{"1234": personinfo{"1", "Jack", "Class 101, ..."},
C. Element assignment mymap["1234"] = PersonInfo {"1", "Jack", "101, ..."}
D. element removal The Go language provides a built-in function delete (), which deletes the element in the container delete (MyMap, "1234")//key-value pairs that have the key "1234" removed from the MyMap, and if the "1234" key does not exist, this call will not happen. If the value of the incoming map variable is nil, the call causes the program to throw an exception.
E. Element lookup in the go language, the map lookup function is designed to be sophisticated. The general practice of judging if a value can be obtained from a map is: (1) declaring and initializing a variable to be empty (2) trying to get the value of the corresponding key from the map into the variable (3) to determine whether the variable is still empty, or null to indicate that the variable is not included in the map
This approach is rather verbose. In the go language, looking for a specific key from the map, this can be done: value, OK: = mymap["1234"] if OK {//found the value of the//process found}
To determine if a particular key has been successfully found, you do not need to check to see if the value is nil, just check the second return value OK.
Mates: = operator, so that your code does not have redundant ingredients, it looks very clear and understandable.
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.