This is the third day of my participation in the August Text Challenge.More challenges in August

Directory:

  • 01. Why do you choose Go
  • 【 hand by hand teach you to write 】02
  • 03. Basic data types
  • 04. Operators and flow control
  • 05. Function
  • 06. Project management
  • 07. Compound types – Pointers
  • 08. Compound types – arrays and slices
  • 08. Complex types -map
  • 09. Complex types – Structures
  • 10. Object-oriented programming
  • 11. Exception handling
  • 12. Text processing
  • 13. Concurrent programming – concurrent entry

The data type for Go is fairly simple. As with C, simple but not simple.

2. Basic types

2.1 named

All function names, variable names, constant names, type names, statement labels and package names in Go follow a simple naming rule:

A name must begin with a letter (Unicode letter) or underscore, and can be followed by any number of letters, numbers, or underscores.

Upper and lower case letters are different: heapSort and heapSort are two different names.

There are 25 (all lowercase) keywords like if and switch in Go. Keywords cannot be used for custom names and can only be used in specific syntax structures.

break       default         func         interface        select
case        defer           go           map              struct
chan        else            goto         package          switch
const       fallthrough     if           range            type
continue    for             import       return           var
Copy the code

In addition, there are about 30 predefined names, such as int and true, that correspond to built-in constants, types, and functions.

Built-in constants: true false iota nil Built-in types: int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr float32 float64 complex128 complex64 bool byte rune Make len cap new append copy close delete complex real imag panic RecoverCopy the code

2.2 variable

A basic component of almost any programming language, variables are quantities that can be changed while a program is running.

Basically, a variable is a name for a piece of data storage. A program can claim a piece of data storage by defining a variable, and then use it by referring to the variable name.

 

2.2.1 Variable declaration

The way variables are declared in Go is markedly different from that in C and C++. For pure variable declarations, the Go language introduces the keyword var, with type information placed after the variable name, as shown in the following example:

Var v1 int var v2 int var v3, v4 int var (v5 int v6 int)Copy the code

2.2.2 Variable Initialization

For scenarios that require initialization when declaring variables, the var keyword can be retained, but is no longer a required element, as shown below:

Var v1 int = 10 var v2 = 10 var v1 int = 10 Println("v3 type is ", reflect.typeof (v3)) //v3 type is int Var v4 int v4 := 2 //err // Note: Auto-derived types can only be used inside functionsCopy the code

2.2.3 Variable Assignment

Var v1 int v1 = 123 var v2, v3, v4 int v2, v3, v4 = 1, 2, 3 I := 10 j := 20 I, j = j, I // multiassignmentCopy the code

 

2.2.4 Anonymous Variables

_ (underscore) is a special variable name, and any value assigned to it is discarded:

_, i, _, j := 1, 2, 3, 4
 
func test() (int, string) {
    return 250, "sb"
}
 
_, str := test()
Copy the code

Use: Reclaim variable, often used to receive the return value of the function, because the go function is allowed to have multiple return values, if only one of them, you can use anonymous variables to discard the other variables.

2.3 constant

In Go, a constant is a value that is known at compile time and cannot be changed. Constants can be numeric (including integer, floating point, and complex), Boolean, string, and so on.

2.3.1 Literal Constants (Constant values)

Literal constants are hard-coded constants in a program, such as:

123 3.1415 // Float type constant 3.2+ 12I // complex type constant true // Boolean type constant "foo" // string constantCopy the code

2.3.2 Constant definition

Variables: Variables that can be changed while the program is running. Variable declarations require var

Constant: a quantity that cannot be changed while the program is running. Constant declarations require const

Const Pi float64 = 3.14 const zero = 0.0 const int64 = 1024 eof = -1 Const u, v float32 = 0, 3 // u = 0.0, v = 3.0, Const a, b, c = 3, 4, "foo" // a = 3, b = 4, c = "foo" //err, constants cannot be changedCopy the code

2.2.3 iota enumeration

Constant declarations can be initialized using the IOTA constant generator, which generates a set of constants initialized with similar rules, but without having to write an initialization expression for each line.

 

In a const declaration, ioTA is set to 0 on the line where the first constant is declared, and then incremented by one on each line where the constant is declared.

Const (x = iota // x == 0 y = iota // y == 1 z = iota // z == 2 w // w == 3 Const v = iota // const v = iota; Const (h, I, j = iota, iota, //h=0, I =0,j=0) const (a= iota //a=0 b = "b" c= iota //c=2 d, e, f = iota, iota, Iota //d=3,e=3,f=3 Const (x1 = iota * 10 // x1 == 0 y1 = iota * 10 // z1 = iota * 10 // z1 == 20) const (x1 = iota * 10 // x1 == 0 y1 = iota * 10 // z1 == 20 (a = iota //0 b //1 c //2 d = "ha" // Iota +=1 e //"ha" iota +=1 f = 100 g //100 ioTA +=1 h = ioTA //7, recovery count I //8) fmt.Println(a,b,c,d,e,f,g,h,i)//0 1 2 ha ha 100 100 7 8Copy the code

2.4 Basic Data types

Against 2.4.1 classification

The following basic types are built into Go:

type The name of the The length of the Zero value instructions
bool Boolean type 1 false Its value is either true or false, and it cannot be represented by numbers as true or false
byte Byte type 1 0 Uint8 alias
rune Character types 4 0 Dedicated to storing Unicode codes, equivalent to uint32
int, uint The integer 4 or 8 0 32-bit or 64-bit
int8, uint8 The integer 1 0 -128 to 127, 0 to 255
int16, uint16 The integer 2 0 -32768 to 32767, 0 to 65535
int32, uint32 The integer 4 0 -2.1 billion to 2.1 billion, 0 to 4.2 billion
int64, uint64 The integer 8 0  
float32 floating-point 4 0.0 The decimal place is accurate to seven places
float64 floating-point 8 0.0 The decimal place is accurate to 15 places
complex64 The plural types 8    
complex128 The plural types 16    
uintptr The integer 4 or 8   The uint32 or uint64 integer that is sufficient to store Pointers
string string   “” Utf-8 string

2.4.2 Boolean type

Var v1 bool v1 = true v2 := (1 == 2) var v1 bool v1 = true v2 := (1 == 2) Automatic or forcible type conversion is not supported var b bool b = 1 // err, compilation error b = bool(1) // err, compilation errorCopy the code

Bool turn int

func bool2int(b bool) int {
    if b {
        return 1
    }
    return 0
}
Copy the code

Turn int bool

func int2bool(i int) bool {
    return i != 0
}
Copy the code

2.4.3 integer

Var v1 int32 v1 = 123 v2 := 64 // v1 will be automatically inferred as an intCopy the code

The difference between an int and a uint is that a u, with a U, means unsigned, and no u means signed.

Explain the difference between this symbol:

Take Int8 and Uint8 as examples. 8 represents 8 bits and can represent 2^8 = 256.

  • Uint8 is unsigned and can represent all positive numbers, 0-255, just 256 numbers.
  • Int8 is signed, it can be positive or negative, so what do I do? Split it in half. -128-127, which is exactly 256 numbers.

Int8 int16 int32 int64 Each of these types has a number at the end, indicating that they can represent a fixed number of values.

Int does not specify its number of bits, which means that its size can change. By what?

  • When you’re on a 32-bit system, both ints and uints take up 4 bytes, or 32 bits.
  • If you’re on a 64-bit system, both ints and uints take up 8 bytes, or 64 bits.

For this reason, in some cases you should avoid using int and uint in favor of the more precise int32 and int64, such as in binary transfers, reads and writes (to keep the structure of the file unaffected by the length of bytes on different compilation platforms).

2.4.4 floating-point

Var f1 float32 f1 = 12 f2 := 12.0 // If no decimal point is added, fValue2 is derived to an integer instead of a floating-point, float64Copy the code

Float32 and float64

The Go language provides floating-point numbers float32 and float64 with two precision.

Float32, also known as single-precision, is stored in 4 bytes, i.e. 4*8=32 bits, of which 1 bit is used for symbol, 8 bits are used for exponent and the remaining 23 bits represent mantissa

Float64, also known as double precision, stores eight bytes, or 8*8=64 bits, of which one is used for symbols, 11 for exponents, and the remaining 52 bits for mantissa

So what does precision mean? How many significant bits are there?

The accuracy depends mainly on the number of digits in the mantissa.

In float32, the number of mantissa is 23 bits, except for all zeros, and is at least 2^-23 (1.19*10^-7). Float is accurate to the last six digits plus the significant digit before the decimal point.

Similarly, float64 (single precision) has a 52-digit mantissa with a minimum of 2^-52, which is about 2.22*10^-16, so it is accurate to 15 decimal places plus one place before the decimal point, giving 16 significant digits.

Through the above, the following points can be summarized:

Float32 and float64 can represent many values

Floating-point types can range from very small to very large. The limit of the range of floating-point values can be found in the Math package:

  • Constant math.MaxFloat32 indicates the largest value that float32 can take, which is about 3.4e38;
  • Constant math.MaxFloat64 Indicates the maximum value that float64 can take, which is about 1.8E308;
  • The minimum values of FLOAT32 and float64 are 1.4E-45 and 4.9E-324 respectively.

Second, the value is large but the accuracy is limited

Although other people can represent the value is very large, but the precision bit is not so large.

  • The accuracy of float32 can only provide about 6 decimal numbers (representing 6 decimal places after scientific notation) \
  • Float64 has an accuracy of about 15 decimal numbers (representing 15 decimal places after scientific notation) \

What do I mean by precision here?

For example, the number 10000018, represented in float32, is 1.0000018 * 10^7, which is accurate to 6 decimal places since it has 7 significant bits.

Now, in scientific notation, we have seven decimal places behind the decimal point, which just meets our accuracy requirements. What does that mean? If you do something like plus 1 or minus 1, you’re guaranteed to get the exact answer

import "fmt" var myfloat float32 = 10000018 func main() { fmt.Println("myfloat: ", myfloat) fmt.Println("myfloat: ", myfloat+1)} /* myfloat: 1.0000018e+07 myfloat: 1.0000019e+07 /Copy the code

The above example shows a critical case of data that just meets the accuracy requirement. For comparison, the following example shows an example of data that just does not meet the accuracy requirement. We just have to add one more digit to this number.

If the value is changed to 100000187, the float32 float32 is also used to represent the scientific notation. Due to its limited accuracy, the 7 digits after the decimal point are accurate. However, if the value is mathematically calculated, the value in the seventh digit becomes inaccurate because the eighth digit cannot be represented.

Myfloat01 = 100000182 +5 myFloat02 = 100000187

import "fmt"

var myfloat01 float32 = 100000182
var myfloat02 float32 = 100000187
func main() {
    fmt.Println("myfloat: ", myfloat01)
    fmt.Println("myfloat: ", myfloat01+5)
    fmt.Println(myfloat02 == myfloat01+5)
}
Copy the code

However, since its type is float32, the result of the final comparison is not equal (inaccurate from the seventh decimal place).

Myfloat: 1.00000184 e+08

Myfloat: 1.0000019 e+08

false

Because of the accuracy, myfloat == myfloat +1 will return true.

2.4.5 Character Types

Two character types are supported in the Go language, one is byte (actually an alias for uint8), which represents the value of a single byte of a UTF-8 string; The other is rune, which stands for a single Unicode character.

package main import ( "fmt" ) func main() { var ch1, ch2, Ch3 byte ch1 = 'a' // character ch2 = 97 // ASCII character ch3 = '\n' // escape character ftt. Printf("ch1 = %c, ch2 = %c, %c", ch1, ch2, Printf(" uppercase: %d, lowercase: %d\n", 'A', 'A')// uppercase: 65, lowercase: 97 %c\n", 'A'+32) FMT.Printf(" lowercase to uppercase: %c\n", 'A' -32)}Copy the code

2.4.6 string

In the Go language, strings are also a basic type:

  1. Double quotation marks
  2. A string consists of one or more characters
  3. Strings are hiding the terminator, ‘\0’
Var STR string // declare a string variable STR = "ABC" // string assignment ch := STR [0] // take the first character of string ftt. Printf(" STR = %s, len = %d\n", STR, Printf(" STR [0] = %c, ch = %c\n", STR [0], ch) // '(backquotes) the enclosed string is Raw string, That is, the string is printed in code as it is printed, without character escape, and the newline is printed as it is. Str2 := 'hello mike \n \r test' fmt.Println("str2 = ", str2) /* str2 = Hello Mike \n \r test */Copy the code

2.4.7 Complex type

Complex numbers are actually made up of two real numbers (represented on computers as floating-point numbers), one representing the real part (real) and one representing the imaginary part (iMAG).

Var v1 complex64 // V1 = 3.2 + 12i v2 := 3.2 + 12i // v2 is a complex128 type of complex(3.2, Println(real(v1), imag(v1)); Println(imag(v1));Copy the code

2.5 FMT package formatted output input

2.5.1 Format Description

format meaning
% % A % literal
%b A binary integer value (base 2) or a floating-point number (advanced) of exponent 2 in scientific notation
%c The character type. The input number can be converted to the corresponding character according to the ASCII code
%d A decimal number (base 10)
%e A floating point or complex number represented by scientific notation e
%E A floating point or complex number represented by scientific notation E
%f A floating point or complex value expressed in standard notation
%g Floating-point or complex numbers represented by %e or %f, either of which is printed in the most compact way possible
%G Floating-point or complex numbers represented by %E or %f, either of which is printed in the most compact way possible
%o A number represented in octal (base 8)
%p The address of a value in hexadecimal (base 16), prefixed with 0x, and represented by lowercase a-f
%q Use the Go syntax, and escape when necessary, to slice double-quoted strings or bytes [] bytes, or single-quoted numbers
%s A string. Prints characters in the string up to empty characters in the string (the string ends with ‘\0’, which is the empty character)
%t Boolean value printed as true or false
%T The type of value output using the Go syntax
%U An integer code point in Unicode notation, with a default value of 4 numeric characters
%v A value of a built-in or custom type output using the default format, or a custom value output using a String() of its type, if the method exists
%x An integer value in hexadecimal (base 16) with the numbers a-f in lower case
%X An integer value in hexadecimal (base 16) with the numbers a-f in lower case

2.5.2 output

/ / a: integer = 15 FMT) Printf (" a = % b \ n ", a), / / a = 1111 FMT. Printf (" % % \ n ") / / / / the output only one % character ch: = 'a' FMT) Printf (" ch = % c, % c \ n ", ch, 97), / / a, a / / floating point f: = 3.14 FMT) Printf (" \ n "f = % f, % g, f, f) / / f = 3.140000, 3.14 FMT) Printf (" f type = % T \ n", V := complex(3.2, 12) ftt. Printf("v = %f, %g\n", v, v) //v = (3.200000+12.000000 I), Printf("% T, %T\n", true, false) Printf("% T, %T\n", true, false) //true, False // String STR := "hello go" fmt.Printf(" STR = %s\n", STR) // STR = Hello goCopy the code

2.5.3 input

Var v int fmt.println (" please input an integer: ") fmt.scanf ("%d", &v) // fmt.scan (&v) fmt.println ("v = ", v)Copy the code

2.6 Type Conversion

Implicit conversions are not allowed in the Go language, all type conversions must be declared explicitly, and conversions can only occur between two compatible types.

Var flag bool flag = true fmt.Printf("flag = %t\n", flag) //bool cannot be converted to int fmt.Printf("flag = %d\n", flag) //fmt.Printf("flag = %d\n", flag) Int flag = bool(1) var ch byte ch = 'a' var t int t = int(ch) Println("t = ", t) Println("t = ", t)Copy the code

2.7 Type Aliases

Var x bigint = 100 type (myint int //int mystr string //string mystr)Copy the code