Go Bible Notes-Chapter III

Source: Internet
Author: User
Tags arithmetic operators bitwise first string
This is a creation in Article, where the information may have evolved or changed. The go language divides data types into four categories: the underlying type, the composite type, the reference type, and the interface type.


3.1. Integral type
1) fixed size, int8, Int16, Int32 and Int64, respectively, corresponding to 8, 16, 32, 64bit of the size of the number of signed, and this corresponds to Uint8, UInt16, UInt32 and UInt64 four types of unsigned shaping.


2) Non-fixed size, int and uint, corresponding to 32 or 64bit respectively


3) The Unicode character rune type is a type that is equivalent to int32 and is typically used to represent a Unicode code point. These two names can be used interchangeably. The same byte is also the equivalence type of the uint8 type.


4) There is also an unsigned integer type uintptr, which does not specify a specific bit size but is sufficient to hold the pointer.


5) operator
Arithmetic operators + 、-、 * and/can be applied to integers, floating-point numbers, and complex numbers, but modulo operator% is used only for operations between integers.


The symbol of the% modulo operator is always the same as the symbol for modulo, so the -5%3 and -5%-3 results are-2.


The division operator/'s behavior depends on whether the operand is full integer, such as the result of 5.0/4.0 is 1.25, but the result of 5/4 is 1.


bitwise operator, the preceding 4 operator operators do not distinguish between signed and unsigned numbers:
& Bit arithmetic and
| Bitwise Operation OR
^ Bitwise Operation XOR
&^ bit emptying (and not)
<< left Shift
>> Right Shift


The left shift operation fills the right vacant bit with 0, the right shift of the unsigned number also fills the left vacant bit with 0, but the right shift operation of the signed number fills the left vacant bit with the value of the sign bit. For this reason, it is best to use unsigned arithmetic so that you can treat integers exactly as a bit bit pattern.


The conversion of a floating-point number to an integer loses any fractional parts and then truncates to the axis 0 direction.


The [1] adverb after% tells the printf function to use the first operand again. Second,% of the # adverbs tell printf to generate a 0, 0x, or 0X prefix when outputting with%o,%x, or%x.
x: = Int64 (0xdeadbeef)
Fmt. Printf ("%d%[1]x%#[1]x%#[1]x\n", x)
Output:
3735928559 Deadbeef 0xdeadbeef 0XDEADBEEF




3.2. Floating point number


1) The Go language provides two types of precision floating point numbers, float32 and float64.
A float32 type of floating-point number can provide approximately 6 decimal digits of precision, while float64 can provide a precision of about 15 decimal digits, that is, the number of digits after the decimal point is accurate, it is recommended to use 64-bit


2) If a function returns a floating-point number that may fail, the best practice is to report the failure with a separate flag, like this:
Func compute () (value float64, OK bool) {
// ...
If failed {
return 0, False
}
return result, True
}




3.3. plural
1) The complex types of two kinds of precision: complex64 and complex128. The built-in complex function is used to construct complex numbers, and built-in real and IMAG functions return the real and imaginary parts of the complex numbers, respectively:
var x complex128 = Complex (1, 2)//1+2i
var y complex128 = Complex (3, 4)//3+4i
Fmt. PRINTLN (x*y)//"( -5+10i)"
Fmt. Println (Real (x*y))//"-5"
Fmt. Println (Imag (x*y))//"10"


The declaration statements for X and y above can also be simplified:
x: = 1 + 2i
Y: = 3 + 4i


2) The plural can also be compared with = = and! =. They are equal only when the real and imaginary parts of the two complex numbers are equal (the comparison of the floating-point numbers is dangerous, and the accuracy problem needs to be handled with special care).




3.4. Boolean type


1) The Boolean value is not implicitly converted to a numeric value of 0 or 1, and vice versa.
2) Pay attention to short-circuit condition,&& priority higher than | |




3.5. String
1) The built-in Len function returns the number of bytes in a string (not the number of Rune characters), the index operation S[i] returns the byte value of byte I, and I must satisfy the 0≤i< len (s) condition constraint.


2) If attempting to access a byte beyond the range of the string index will result in a panic exception


3) Sub-string operation S[i:j], I, J can be omitted, value is [0:len (s)]


4) The value of the string is immutable, but you can also assign a new string value to a string variable, noting that it is possible to cause garbage collection


5) native strings use anti-quotes instead of double quotes, which can contain newline characters, but the carriage return character is removed.


6) The Unicode code point corresponds to the rune integer type in the Go language.


We can represent a sequence of runes as a int32 sequence, which is called UTF-32 or UCS-4.


UTF8 is a variable-length encoding that encodes a Unicode code point into a sequence of bytes. The UTF8 encoding uses 1 to 4 bytes to represent each Unicode code point, the ASCII partial character uses only 1 bytes, and the characters commonly used part is represented by 2 or 3 bytes. The high-end bit bit of the first byte after each symbol encoding is used to indicate how many bytes are encoded in total. If the high-end bit of the first byte is 0, it represents ASCII characters corresponding to 7bit, and each character of the ASCII character remains one byte, compatible with the traditional ASCII encoding. If the high-end bit of the first byte is 110, then 2 bytes are required; each subsequent high-end bit begins with 10. A larger Unicode code point is also handled with a similar strategy.
0xxxxxxx runes 0-127 (ASCII)
110xxxxx 10xxxxxx 128-2047 (values <128 unused)
1110xxxx 10xxxxxx 10xxxxxx 2048-65535 (values <2048 unused)
11110xxx 10xxxxxx 10xxxxxx 10xxxxxx 65536-0x10ffff (other values unused)


The Unicode escape character allows us to enter special characters through Unicode code points. There are two forms: \uhhhh corresponding to the 16bit code point value, \uhhhhhhhh corresponding to the 32bit code point value
World
"\xe4\xb8\x96\xe7\x95\x8c"
"\u4e16\u754c"
"\u00004e16\u0000754c"
The above three escape sequences provide an alternative notation for the first string, but their values are the same.


The value of less than 256 yards can be written in a hexadecimal escape byte, such as ' \x41 ' corresponding to the character ' A ', but for larger code points you must use the \u or \u escape form. As a result, ' \xe4\xb8\x96 ' is not a valid rune character, although these three bytes correspond to an effective UTF8 encoded code point.


7) Decode UTF8 string, you can call UTF8. Decoderuneinstring or using range loops, or []rune () conversion
Each UTF8 character is decoded, and if an incorrect UTF8 encoded input is encountered, a special Unicode character of ' \ufffd ' will be generated.


String accepts a type conversion of []rune, which can decode a UTF8 encoded string into a sequence of Unicode characters:
' Program ' in Japanese katakana
S: = "プログラム"
Fmt. Printf ("% x\n", s)//"E3-E3-E3-in-the-B0 E3 A9"
r: = []rune (s)
Fmt. Printf ("%x\n", R)//"[30d7 30ed 30b0 30e9 30e0]"


8) integer to UTF8 string
Transforming an integer to a string means a UTF8 string that is generated to contain only the corresponding Unicode code point characters:
Fmt. PRINTLN (String)//"A", not "65"
Fmt. Println (String (0X4EAC))//"Beijing"


If the character of the corresponding code point is invalid, replace it with the ' \UFFFD ' invalid character:
Fmt. Println (String (1234567))//""


9) Four packages in the standard library are particularly important for string handling: bytes, strings, StrConv, and Unicode packages.
The strings package provides many functions such as querying, replacing, comparing, truncating, splitting, and merging strings.
The bytes package also provides a number of functions similar to the function, but for the []byte type] that has the same structure as the string.
Because strings are read-only, building a string incrementally causes a lot of allocation and replication. In this case, use bytes. The buffer type will be more efficient and we'll show you later.
The StrConv package provides the conversion of Boolean, Integer, floating-point, and corresponding strings, as well as double-quote-escaping-related conversions.
The Unicode package provides similar features such as IsDigit, Isletter, Isupper, and Islower, which are used to categorize characters.
The path and Path/filepath packages provide more general function operations on file path names.
Path uses slashes to separate paths and can work on any operating system. The Path/filepath package uses the path rules of the operating system itself, such as POSIX systems using/foo/bar, while Microsoft Windows uses C:\foo\bar and so on.
The bytes package also provides a buffer type for the cache of byte slice. A buffer is initially empty, but writes of type data such as String, Byte, or []byte] can grow dynamically.




3.6. Constants
1) A declaration of a constant can also contain a type and a value, but if the type is not explicitly indicated, the type is inferred from the expression on the right.
Const Nodelay time. Duration = 0
Const TIMEOUT = 5 * time. Minute


2) If it is a batch declaration of a constant, in addition to the first other than the constants to the right of the initialization expression can be omitted, if the initialization expression is omitted, it represents the same value, type and initialization expression of the preceding constant. For example:
Const (
A = 1
B
c = 2
D
)
Fmt. Println (A, B, C, D)//"1 1 2 2"


3) Iota Constant declaration initializer
In a const declaration statement, the first row that appears iota will be set to 0 and then add one to each row with a constant declaration.


4) No type constant
The compiler provides arithmetic operations that have a higher precision than the underlying type for numeric constants of these types that do not have a definite underlying type, and can be considered to have at least 256bit of computational precision. There are six types of constants that are not explicitly typed, such as untyped booleans, untyped integers, untyped characters, untyped floating-point numbers, untyped complex numbers, and untyped strings.


Math. Pi is a non-type floating-point constant that can be used directly in any place where a floating-point or complex number is required:
var x float32 = Math. Pi
var y float64 = Math. Pi
var z complex128 = Math. Pi


For example, 0, 0.0, 0i, and ' \u0000 ' have the same constant values, but they correspond to different constant types, such as untyped integers, untyped floating-point numbers, untyped complex numbers, and untyped characters.


Only constants can be untyped. When an untyped constant is assigned to a variable, the untyped constant is implicitly converted to the corresponding type, if the conversion is valid.
var f float64 = 3 + 0i//untyped complex-float64
F = 2//untyped integer--float64
f = 1e123//untyped floating-point-float64
f = ' a '//untyped Rune-Float64
The above statement is equivalent to:
var f float64 = float64 (3 + 0i)
f = float64 (2)
f = float64 (1e123)
f = float64 (' a ')


For a variable declaration syntax that does not have an explicit type (including the short variable declaration syntax), an untyped constant is implicitly converted to the default variable type, as in the following example:
I: = 0//untyped integer; implicit int (0)
r: = ' \000 '//untyped rune; Implicit rune (' \000 ')
F: = 0.0//untyped floating-point; implicit float64 (0.0)
c: = 0i//untyped complex; Implicit complex128 (0i)
Note The default type is regular: An untyped integer constant is converted by default to int, which corresponds to an indeterminate memory size, but floating-point numbers and complex constants are converted by default to Float64 and complex128.
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.