当前位置:网站首页>Understanding_Data_Types_in_Go

Understanding_Data_Types_in_Go

2022-08-10 14:59:00 15231181628

Understanding_Data_Types_in_Go

理解 Go 的数据类型

介绍

Data type refers to the written application specific variables store the type of the value of the.Data type also determines the operation of data which can perform.

在本文中,我们将介绍 Go An important data type of itself.This article is not to the data type of detailed survey,But will help you to familiar with Go 中可用的选项.Some basic data types will be able to understand that you can write more clearly the code,So as to more effectively perform.

背景

A kind of method is to consider our to understand the data type in different types of data used in the real world.An example of real world data is a digital: 例如,We can use unsigned integer(0,1,2,...)、有符号整数(... ,-1,0,1,...)and irrational numbers(π).

通常,在数学中,We can use different types of digital combination,To get an answer.例如,我们可以把 5 加到 π 上:

5 + π

We can put this equation as the answer because of irrational Numbers,也可以把 π The abbreviation of approximate rounding to decimal Numbers,Put these Numbers together again:

5 + π = 5 + 3.14 = 8.14 

但是,If we begin to try to use another data type,Such as words to calculate the Numbers,Will become less meaningful.We how to work out the formula below?

shark + 8

对于计算机来说,Is a big difference for each data type,As words and Numbers.因此,For different data types of the assignment and modification operations,我们必须谨慎.

整数

和数学一样,In computer programming 整数 可以是正数、负数或者 0(... -1,0,1,...).在 Go 中,Integers are called int.与其他编程语言一样,Should not use commas in four digits or more digital,So in the program to write 1,000 时,please write as 1000.

We can print an integer to the following simple this way:

fmt.Println(-459)
output
-459

或者,我们可以声明一个变量,In this case is we are used to represent and manipulate digital symbol,如:

var absoluteZero int = -459
fmt.Println(absoluteZero)
output
-459

我们也可以在 Go The integer calculation.在下面的代码块中,我们将使用 := Assignment operator to declare and instantiate the variables sum

sum := 116 - 68
fmt.Println(sum)
output
48

如输出所示,数学算子 -116 Subtract integers 68,得到 48.你将在声明变量的数据类型Section for more information about the variable declaration.

在 Go 程序中,There are a variety of ways to use the integer.As you continue to learn Go,You will have many opportunities to use integers and on the basis of the data types of knowledge to build.

浮点数

浮点数float Used to represent a cannot be represented as an integer实数.Real Numbers include all rational Numbers and irrational Numbers,因此,Floating point Numbers can contain the decimal part,比如 9.0 或 -116.42.Go Application of floating point Numbers,Can be thought of as a contains the number of decimal point.

As we handle integer,We can use such a simple way to print out a floating point number:

fmt.Println(-459.67)
output
-459.67

We can also declare a variable said floating-point,如:

absoluteZero := -459.67
fmt.Println(absoluteZero)
output
-459.67

Similar to integers,我们也可以在 Go Calculation of floating point Numbers:

var sum = 564.0 + 365.24
fmt.Println(sum)
output
929.24

对于整数和浮点数,记住 3 ≠ 3.0 很重要,因为 3 表示的是一个整数,而 3.0 表示的是一个浮点数.

数字类型的大小

In addition to the difference between integer and floating point Numbers,Go There are two types of numerical data,The two numerical data by the size of the static or dynamic characteristics to distinguish.The first type is with_体系结构无关_的类型,This means that no matter where the code to run on the machine,For a unit of data will change the size of the.

Most of today's system architecture are32位或64位的.例如,You may be a modern Windows Laptop development,The operating system running in Windows 64位架构上.然而,If you are a like fitness watch equipment development and application of,You are likely to use a32位的架构.如果你使用像 int32 That is independent of the type of architecture,So no matter how you to compile architecture,This type will have a fixed size.

第二种是_Implementation dedicated_的类型.在这种类型中,A size can be according to the program's architecture varies.例如,如果我们使用 int 类型,当 Go 为 32 An architecture compile time,The size of the data types will be 32 位.If the program is to 64 A compilation of the architecture,The variable size is 64 位.

In addition to the data types in different sizes,Similar to an integer type there are two basic types: _有符号_和_无符号_.int8 是一个有符号整数,可以取 -128 到 127 之间的值.uint8 是一个无符号整数,只能取 0 到 255 Is between the numeric.

Related to the size of the scope and a.对于二进制数据,8 Who can represent a total 256 个不同的值.因为 int Type need to support both positive and negative,所以 8 位整数(int8)的范围是 -128 到 127,总共有 256 个不同的值.

Go Has the following has nothing to do with the architecture of the integer type:

uint8       unsigned  8-bit integers (0 to 255)
uint16      unsigned 16-bit integers (0 to 65535)
uint32      unsigned 32-bit integers (0 to 4294967295)
uint64      unsigned 64-bit integers (0 to 18446744073709551615)
int8        signed  8-bit integers (-128 to 127)
int16       signed 16-bit integers (-32768 to 32767)
int32       signed 32-bit integers (-2147483648 to 2147483647)
int64       signed 64-bit integers (-9223372036854775808 to 9223372036854775807)

The size of the floating point number and plural is change:

float32     IEEE-754 32-bit floating-point numbers
float64     IEEE-754 64-bit floating-point numbers
complex64   complex numbers with float32 real and imaginary parts
complex128  complex numbers with float64 real and imaginary parts

There are also some numeric type alias,By assigning useful to represent the name of the specific data types:

byte        alias for uint8
rune        alias for int32

byte Alias made it clear that the program is the purpose of when to use the byte string element as the commonly used computing measure,Rather than a has nothing to do with the byte data measurement of small integer.Although the program compiled byteuint8 是相同的,但 byte Usually used to represent a digital character data in the form of,而 uint8 Is used to show the number in the program.

rune The alias is a bit different.如果 byteuint8 Are the same data,那么 rune Can be a byte, or four bytes,This range is determined by int32 决定.rune 用来表示 Unicode 字符,而只有 ASCII Characters can be made by int32 Data type separate said.

此外,Go And the following specific implementation type:

uint     unsigned, either 32 or 64 bits
int      signed, either 32 or 64 bits
uintptr  unsigned integer large enough to store the uninterpreted bits of a pointer value 

Specific implementation type size will be decided by the program compiled the architecture of the.

Select the numerical data type

Choose the correct size is usually more programming function for the performance of the target architecture,Rather than the size of the data processing.但是,Don't need to know the performance of application specific impact,Before you can begin to follow some basic guidelines.

正如本文前面所讨论的,Has nothing to do with architecture types and specific implementation type.For integer data,Go 中通常使用 intuint and other implementation types,而不是 int64uint64.This usually target architecture with the fastest speed for you.例如,如果使用 int64 并将其编译为 32 The application of an architecture,Then deal with the value of the time required to spend at least one times,Because in the framework of mobile data need extra CPU 周期.如果使用 int,The program will define it as 32 位体系结构的 32 位大小,And handling it would be much faster.

If you know you can't more than the size of the specific range,Then choose the type of has nothing to do with the system structure can improve the speed,Can reduce memory use again.例如,If you know your data will not exceed 100,And just a positive,那么选择 uint8 Will make your program more efficient,Because it requires less memory.

Now that we have seen some possible range of numerical data type,Let's see if what will happen in the program over the range.

溢出 vs. 折叠

When you try to store a greater than design store the data type of the value,Go 有可能会_溢出_和_折叠_一个数字,Depending on the value is at compile time or at run time calculation.When the program is found errors when trying to build the program,A compile-time error occurs.程序编译完成后,In the process of actual execution is a runtime error occurs.

在下面的例子中,我们将 maxUint32 Set to a maximum of it:

package main

import "fmt"

func main() {
 var maxUint32 uint32 = 4294967295 // Max uint32 size
 fmt.Println(maxUint32)
}

The operation of the compiled the results are as follows:

output
4294967295

If we are on the value added at run time 1,It will be folded into 0

output
0

另一方面,我们修改程序,Before assigning value and compile and 1

package main

import "fmt"

func main() {
 var maxUint32 uint32 = 4294967295 + 1
 fmt.Println(maxUint32)

}

在编译时,If the compiler can determine whether a value is too big to be saved in a specified data type,它将抛出 overflow 溢出错误.This means that the calculation of the value for a specified data type is too big.

Because the compiler can determine it will overflow value,It throws a mistake now:

outputprog.go:6:36: constant 4294967296 overflows uint32

Understanding the boundary of the data will help you to avoid possible errors in the program in the future.

Now we have introduced a numeric type,Let's take a look at how to store the Boolean value.

布尔值

boolean Data types can values from the two values,即 truefalse,In a statement for the data types defined as bool.Boolean value used to represent the true value of mathematical logic branch related,It provides algorithm in computer science with information.

truefalse Will always use lowercase respectively tf,因为它们是 Go 中预先声明的标识符.

Many mathematics answers that are either true or false:

  • 大于
    • 500 > 100 true
    • 1 > 5 false
  • 小于
    • 200 < 400 true
    • 4 < 2 false
  • 等于
    • 5 = 5 true
    • 500 = 400 false

Similar to the digital,We can use a variable to hold the Boolean value:

myBool := 5 > 8

接下来我们可以调用 fmt.Println() Function to print Boolean value:

fmt.Println(myBool)

因为 5 小于 8, We will get the following output:

output
false

随着你在 Go Write more and more applications in,You will be more and more familiar with Boolean value is how to work,As well as the different functions and operating the calculation for the truefalse How will change the course of the program.

字符串

String is made up of one or more characters(字母、数字、符号)组成的序列,These characters can be const,也可以是变量.String in Go 中的反引号 ``` 或 " 中,And according to the different characteristics of use quotation marks with.

如果使用反引号,就是创建了一个_原始_字符串.如果使用双引号,就是创建了一个_解释_字符串.

原始字符串

The original string literal is a character sequence between the quotes,通常称为反引号.在引号中,In addition to the quote character itself,Between the quotation marks any characters will show.

a := `Say "hello" to Go!`
fmt.Println(a)
output
Say "hello" to Go!

通常,The backslash is used to represent special characters in a string.例如,In explaining the string,\n Said a string of new line.但是,The backslash there is no special meaning in the original string:

a := `Say "hello" to Go!\n`
fmt.Println(a)

Because there is no special meaning a backslash in the string literal,It actually prints out \n 的值,Instead of creating a new line of:

output
Say "hello" to Go!\n

The original string can also be used to create a multi-line string:

a := `This string is on 
multiple lines
within a single back 
quote on either side.`

fmt.Println(a)
output
This string is on 
multiple lines
within a single back 
quote on either side.

In front of the block of code,The new guild literally from input to output.

解释字符串

Explain strings are sequences of characters between the double quotes,如 "bar" 中所示.在引号中,Besides newline and not escape the double quotes,Any character can appear.To explain the string shown in double quotes,Can use the backslash as escape character,如下所示:

a := "Say \"hello\" to Go!"
fmt.Println(a)
output
Say "hello" to Go!

You almost always use to explain a string,Because they are allowed to use escape characters in them.Want to know more information about the string to use,请查看[Go The use of string profile]({{< relref "/docs/08-An_Introduction_to_Working_with_Strings_in_Go.md" >}}).

UTF-8 字符的字符串

UTF-8 是一种编码方案,Used to variable width character encoding is one to four bytes.Go 支持开箱即用的 UTF-8 字符,Don't need any special Settings、library or package.像字母 A The Roman characters can be used as digital65这样的 ASCII 值表示.但是,如果使用特殊字符,例如The international character,则需要 UTF-8.Go 对 UTF-8 数据使用 rune 别名类型.

a := "Hello, 世界"

你可以在 for 循环中使用 range Keyword to index Go 中的任何字符串,甚至是 UTF-8 字符串.for 循环和 range Will be discussed in more depth later in this series; 现在,It is important to know that we can use it to calculate the number of bytes in a string given:

package main

import "fmt"

func main() {
 a := "Hello, 世界"
 for i, c := range a {
  fmt.Printf("%d: %s\n", i, string(c))
 }
 fmt.Println("length of 'Hello, 世界': "len(a))
}

在上面的代码块中,我们声明了变量 a,并为其赋值 Hello,世界.Distribution of text contained in the UTF-8 字符.

Then we used a standard for 循环以及 range 关键字.在 Go 中,range Key will be sent to you by string index,每次返回一个字符,As well as the characters in a string of bytes index.

使用 fmt.Printf 函数中,We have provided a format string %d:%s\n.%d Is a digital print verb(In this case, the integer),%s Is a string of print verb.然后我们提供了 i 的值,它是 for Loop current index,cfor In the loop current character.

最后,我们使用内建的 len 函数打印了变量 a 的整个长度.

在前面,我们提到了 rune 是 int32 的别名,Can consist of one to four bytes. Characters need three bytes to define,当通过 UTF-8 String loop,Index also will move accordingly.This is when it is printed out i Is not the cause of the order.

output0: H
1: e
2: l
3: l
4: o
5: ,
6:
7: 世
10: 界
length of 'Hello, 世界':  13

如你所见,The length of the string is bigger than its loop iteration number.

You don't always use UTF-8 字符串,But when used,You will understand why they are called rune 而不是单个 int32.

声明变量的数据类型

Now that you have to understand the different basic data types,接下来我们将讨论如何在 Go Will these types assigned to the variable.

在 Go 中,我们可以使用关键字 var ,Followed by required for variable names and data types to define a variable.

在下面的示例中,We will declare a type of float64 的变量 pi.

关键字 var Is the first statement:

`var` pi float64

Followed by our variable name,pi

var `pi` float64

最后是数据类型 float64

var pi `float64`

We also have specified the initial value of the option,比如 3.14

var pi float64 = `3.14`

Go 是一种_静态类型_语言.Static type means check each statement in the program at compile time.It also means that the data types are bound to the variable,And in the language of the dynamic linking is a data type is bound to the value.

例如,在 Go 中,当声明一个变量时,type is declared:

var pi float64 = 3.14
var week int = 7

If you declare these variables in different ways,Each of them is likely to be different data types.

这与 PHP 语言不同,Its data type that is associated with values:

$s = "sammy";         // $s is automatically a string
$s = 123;             // $s is automatically an integer

In front of the block of code,第一个 $s 是一个字符串,Because it is assignment as "sammy",第二个是一个整数,因为它的值为 123.

接下来,Let's take a look at the more complex data types,比如数组.

数组

_数组_Is an orderly sequence of elements.An array of capacity is defined when creating.Once an array assigned its size,It can't change the size of the.Because the size of the array is static,This means that it only allocate a memory.This makes the array stiff,But increase the performance of the program.因此,An array is typically used for optimization program.接下来介绍的_切片_更加灵活,Its array in other languages with you know more similar.

An array is defined by declaring an array size,And then the data types and define the curly braces { }之间的值.

An array of strings as shown below:

[3]string{"blue coral""staghorn coral""pillar coral"}

We can put the array stored in the variable and print it out:

coral := [3]string{"blue coral""staghorn coral""pillar coral"}
fmt.Println(coral)
output
[blue coral staghorn coral pillar coral]

上面提到过,切片和数组类似,But more flexible.Let's take a look at the variable data types.

切片

一个_切片_Is a can change the length of the sequence of elements in order.Slicing can dynamically increase the size of them.When you add new elements to a section of,If this section does not have enough memory to store the new element,It will according to the need to apply for more memory from the system.Due to the expansion of can according to need to slice to add more elements,So they are more common than array.

Section is defined by declaring in front of the open and close brackets [] 的数据类型,And the curly braces {} 之间有值.

Integer section as shown below:

[]int{-3-2-10123}

The biopsy of the floating point number as shown below:

[]float64{3.149.23111.11312.121.05}

The biopsy of the string as shown below:

[]string{"shark""cuttlefish""squid""mantis shrimp"}

We define a character section is called seaCreatures

seaCreatures := []string{"shark""cuttlefish""squid""mantis shrimp"}

We can print by calling the variable:

fmt.Println(seaCreatures)

The output will be exactly the same as the list and we create:

output
[shark cuttlefish squid mantis shrimp]

We can use the append keyword to add an item to our slice. The following command will add the string value of seahorse to the slice: 我们可以使用 append 关键字,在切片中添加一个元素.The following command will add the string value in the section of seahorse

seaCreatures = append(seaCreatures, "seahorse")

You can print to verify did add this element:

fmt.Println(seaCreatures)
output
[shark cuttlefish squid mantis shrimp seahorse]

如你所见,If you need to manage the elements of an unknown length,Slice will be more appropriate than the data.

Maps

_map_是 Go The built-in hash or dictionary type. Map 使用 _值_对来存储数据.In programming quickly by index or in Go Very useful when through key to find the value in.比如,你可能会用 map 按用户 ID For the index to save users.Keys can be user ID,The user can object is value.map 可以用 map 关键字,Then put the key data type [] 中括号里,Is followed by the data type of the value,And the key/value pair in the curly braces.

map[key]value{}

Commonly used to hold the data related,比如包含 ID 的信息,map 如下所示:

map[string]string{"name""Sammy""animal""shark""color""blue""location""ocean"}

你将注意到,除了大括号之外,整个 map There is also a colon in it.The colon is the key on the left side of the word.键可以是 Go 中的任何_可比较的_类型.Comparable type is some basic types of,如 stringsints 等.Basic type is defined by the language,Rather than through the combination of any other types of building.Although they can be user defined type,But in order to avoid programming errors,Keep them simple is considered best practice.The key is in the dictionary: nameanimalcolorlocation.

The colon is the right word value.Values can be of any data type.The above is the values in the dictionary: Sammy,shark,blueocean.

让我们把 map 存储在一个变量中,然后打印出来:

sammy := map[string]string{"name""Sammy""animal""shark""color""blue""location""ocean"}
fmt.Println(sammy)
output
map[animal:shark color:blue location:ocean name:Sammy]

如果我们只想打印 Sammy 的颜色,可以通过调用 sammy["color"] 的方式完成.我们把它打印出来:

fmt.Println(sammy["color"])
output
blue

因为 map Keys are provided-Ways to store values,在你的 Go They will be important element in the program.

结论

此时,你应该对 Go Available in some of the key data type has a better understanding of.当你使用 Go Language development programming project,Each of these data types will become very important.

一旦掌握了 Go 中可用的数据类型,就可以学习如何转换数据类型,According to particular case in order to change the data type.


2022 GopherChina大会报名仍在火热进行中!

GopherThey scan the qr code below to sign up to participate in oh~

大会合作、现场招聘及企业购票等事宜请联系**微信:18516100522**
原网站

版权声明
本文为[15231181628]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/222/202208101431161449.html