Golang basic quick start basic types

Due to last year's project, the service of the partner was developed by Golang, and simple discussion was also conducted during the cooperation. In addition, the languages of Go and Rust are very popular nowadays 🔥, Finally decided to learn the language system. Start with the most basic features and grammar of the language. After all, they have studied other development languages. Based on the simplicity of Go language itself, learning and getting started are relatively smooth. When studying, I like to take some notes while reading. After finishing and improving a little some time ago, I'll write a blog.

  • 📖 The main textbooks for reference are Go language fun Guide (currently only the English version can be found on the Internet.) Go language practice And Go Web programming, which also includes some online blogs and tutorials,;
  • 📓 Each lesson also contains a sample source code and a note, which simply and systematically records the relevant knowledge points and some of their own understanding;
  • 🐶 Because before learning Golang, many people had the foundation of other languages, so there is no need to study the grammar that is too basic;
  • Source address: https://github.com/Xuhy0826/Go-Go-Study

value type

real number

Floating point type

There are two floating point types in go language:

  1. Float64 (8 bytes of memory), the default floating point type. This means that if float32 is not explicitly specified, float64 is used to define a variable with a decimal point
  2. float32 (4 bytes of memory)
days := 365.2425    //Short declaration, days will be inferred by the Go compiler as the floating point type, and the default float64 type

If we need to use float32, we must specify the type

var pi64 = math.Pi      
var pi32 float32 = math.Pi  //The declared variable will be float32

Zero value

A value of zero is the default value of a type. In Go, when a variable is created but not assigned a value, Go will automatically assign a zero value of the corresponding type to it. The zero value of floating-point type is easy to think of

var price float

Equivalent to

price := 0.0

Format output floating point values

FMT is required for formatted output Printf() function:

fmt.Printf("%f\n", third)     //0.333333
fmt.Printf("%.2f\n", third)   //0.33,. 2f means to keep 2 digits after the decimal point
fmt.Printf("%4.2f\n", third)  //0.33, 4.2f means the total width (length) is 4, and 2 digits are reserved after the decimal point
fmt.Printf("%5.2f\n", third)  //0.33, 5.2f indicates that the total width (length) is 5, and 2 digits are reserved after the decimal point. If the length is not enough, use spaces to fill in
fmt.Printf("%05.2f\n", third) //00.33 and 05.2f indicate that the total width (length) is 5, and 2 digits are reserved after the decimal point. If the length is not enough, use "0" to make up

Precision of floating point type

Since computers can only represent floating-point numbers by 0 and 1, floating-point numbers are often affected by rounding errors, such as:

piggyBank := 0.1
piggyBank += 0.2
fmt.Println(piggyBank) //0.30000000000000004

The accuracy of floating-point types mentioned above will lead to unexpected comparison of floating-point numbers.

fmt.Println(piggyBank == 0.3) //false

A compromise solution is to use a certain degree of accuracy to determine whether they are equal

fmt.Println(math.Abs(piggyBank-0.3) < 0.0001) //true

In the final analysis, the best way to avoid the problem of floating-point accuracy is not to use floating-point numbers 🐶

integer

Go provides 10 types of integers, which are divided into different types according to different sizes and whether there are symbols

  • int8 1 byte (8 bits)
  • uint8 1 byte
  • int16 1 byte
  • uint16 1 byte
  • int32 1 byte
  • uint32 1 byte
  • int64 1 byte
  • uint64 1 byte
  • The other two are int and uint. Go will infer the type of int by default when inferring the type. In go, the int type will select the appropriate bit length according to the target hardware (whether the computer is 32-bit or 64 bit) (int is the 32-bit value on the 32-bit machine and 64 bit length on the 64 bit machine). Therefore, if you want to operate a particularly large number on the 32-bit machine, you should define it as int64 instead of int. But don't think that int type and int32 or int64 are one type. They are three types.

Select the appropriate type

Adapt to different common and choose different types [example]: using uint8 to represent the color rgb value is a good choice:

  • (1) It can limit variables to legal range
  • (2) For uncompressed images, which need to store a large number of colors in order, it can greatly save space
var red, green, blue uint8 = 0, 141, 213
fmt.Printf("color: #%02x%02x%02x;", red, green, blue) //color: #008dd5;

wrap around

Integer type will not have the precision problem of floating-point type, but it has its own looping problem. That is, when the integer type reaches its boundary value (maximum or minimum), and then extends outside the boundary, it will return to the minimum or maximum value. For example, for a uint8, its maximum value should be 255. At this time, after adding 1, the value becomes 0. In fact, as long as you know the binary storage mode of integer in the computer, this thing is still very easy to understand.

var numberA uint8 = 255	//Type maximum reached
numberA++
fmt.Println(numberA)	//0 	 surround

Large number

As the name suggests, it is a particularly large number. Generally, we can also use a simple expression method for a relatively large number (similar to scientific counting method):

var distance int64 = 41.3e12    //41.3 * 10 < sup > 12 < / sup >

However, if we need to use more than the upper limit of uint64, Go provides us with a big package to solve the problem. When quoting, the package name is "math/big".

big package

  • Store large integer: big Int
  • Store floating point numbers of arbitrary precision: big Float
  • Store scores such as 1 / 3: big Rat

big.Int can be created in two ways

  1. Use big Method of newint (int VAL)
lightSpeed := big.NewInt(299792)
  1. Use big Setstring (string, Val, 10), where "10" indicates parameter 1. This string is a decimal number
distance := new(big.Int)
distance.SetString("24000000000000000000000", 10)

Large number types can accurately carry large numbers, but the cost is the loss of space and performance.

Representation of large numbers in constants

Unlike variables, when we do not specify a type for constants and directly assign a large number to them, Go will directly mark them as untyped without throwing overflow exceptions, and can be used normally in programs

const distance = 240000000000000000000000
fmt.Println("Andromeda Galaxy is ", distance/299792/86400)  //output: Andromeda Galaxy is  9265683466462

String type

string type

As for the string type, it is no different from other languages. It is enclosed in double quotation marks, such as

peace := "peace"
var peace = "peace"
var peace string = "peace"

A string enclosed in double quotation marks is called a "string literal". "String literal" can contain escape characters. For example, \ n can represent line break. Another way to represent string literals is to use backquotes, which are called "original string literals". Using ` `, you can easily define cross line strings, such as

fmt.Println(`
peace be upon you
upon you be peace`)

Both "string literal" and "original string literal" are of type string.

Characters, code points, symbols, and bytes

  • We all know that the characters in the computer are accessed by coding, that is, each character is represented by A specific number. For example, A is 65, so this 65 is called the code point of character A in the book.
  • rune type (rune type): in Go, rune type is used to represent the code point of characters. This type is essentially an alias of int32 type, that is, rune and int32 can be converted to each other
  • Byte type: the byte type in Go can not only represent binary data, but also be used to represent ASCII code (ASCII contains 128 characters in total). In essence, byte type is an alias of uint8 type
var pi rune = 960
var alpha rune = 940
var omega rune = 969
var bang byte = 33

fmt.Printf("%v %v %v %v\n", pi, alpha, omega, bang) //960 940 969 33
//Code points can be represented as characters by using the format variable% c
fmt.Printf("%c %c %c %c\n", pi, alpha, omega, bang) //π ά ω !

In Go, single quotation marks are used to represent the literal amount of characters. If the user declares a character variable without specifying its type, Go will infer it as rune type. The following three writing methods have the same function.

grade := 'A'
var grade = 'A'
var grade rune = 'A'

The string cannot be modified

Although strings are "strung" with characters, like C#, java and other languages, the string type in Go cannot be modified.

//Access the characters in the string by index
message := "shalom"
c := message[5]
fmt.Printf("%c\n", c)

//The string cannot be modified
//Message [5] ='d '/ / error: cannot assign to message[5]

Strings and symbols

Strings in Golang are encoded using utf-8. utf-8 is a variable length encoding method, that is, the length of each character may occupy different byte lengths. For example, Chinese characters need to occupy two bytes, while English characters or numbers only need to occupy one byte.
For convenience, Go provides the utf package, which provides two practical methods

  • RuneCountInString function can return the number of characters in the string according to specific characters, instead of returning the length of bytes like len method
  • The DecodeRuneInString function decodes the first character of the string and returns the byte length occupied by the decoded character
question := "What day is it today?"
fmt.Println(len(question), "bytes")                    //18 bytes
fmt.Println(utf8.RuneCountInString(question), "runes") //6 runes

c, size := utf8.DecodeRuneInString(question)
fmt.Printf("First rune: %c %v bytes", c, size) //First run: 3 bytes

//Traverse the strings and print them one by one
for i, c := range question {
    fmt.Printf("%v %c\n", i, c)
}

In the above example, the range keyword is used for traversal, where i is the index and c is the value. It smells like python. Type conversion

In Go, similar to other strongly typed languages (such as C#), operations between types need to undergo type conversion, otherwise an error of "type mismatch" will be reported.

Digital type conversion

  • Integer type → floating point type:
age := 41
marsAge := float64(age)
  • Floating point type → integer type:

[note]: the decimal part of floating-point type is truncated, not rounded

earthDays := 365.2425
fmt.Println(int(earthDays)) //output: 365

When converting numeric types, you should also pay attention to problems beyond the range, such as when a large float64 is converted to int16.

String conversion

  • rune/byte → string
var pi rune = 960
var alpha rune = 940
fmt.Println(string(pi), string(alpha)) //output: π ά
  • Numeric type → string

In a special case, in order to convert a string array to a string type, each number must be converted to a corresponding code point (char). That is, 48 representing character 0 ~ 57 representing character 9. We need to use the Itoa function provided by strconv (for "string conversion") package to complete this work.

countdown := 10
str := "Launch in T minus " + strconv.Itoa(countdown) + " seconds".

Another method is to use FMT Sprintf function, which returns the formatted string instead of printing

countdown := 9
str := fmt.Sprintf("Launch in T minus %v seconds", countdown)
fmt.Println(str) //Launch in T minus 9 seconds
  • string → number is a less commonly used conversion. It also uses the Atoi function of strconv package
count, err := strconv.Atoi("10")
if err != nil {
    //error
}
fmt.Println(count) //10

The above way of writing is often seen later. It is a common way for Go to handle exceptions. Since the Go function can return multiple values, it will generally return the possible exceptions together.

Boolean type conversion

If the Print function of fmt is used to Print the bool type directly, the text of true or false will be output

launch := false
launchText := fmt.Sprintf("%v", launch)
fmt.Println("Ready for launch:", launchText) //Ready for launch: false

In some languages, 1 and 0 are regarded as true and false, but not in Go.

Posted by theslinky on Mon, 18 Apr 2022 08:00:41 +0930