golang数据类型_了解Go中的数据类型

golang数据类型

介绍 (Introduction)

Data types specify the kinds of values that particular variables will store when you are writing a program. The data type also determines what operations can be performed on the data.

数据类型指定在编写程序时特定变量将存储的值的类型。 数据类型还确定可以对数据执行哪些操作。

In this article, we will go over the important data types native to Go. This is not an exhaustive investigation of data types, but will help you become familiar with what options you have available to you in Go. Understanding some basic data types will enable you to write clearer code that performs efficiently.

在本文中,我们将介绍Go固有的重要数据类型。 这不是对数据类型的详尽研究,但可以帮助您熟悉Go中可用的选项。 了解一些基本数据类型将使您能够编写更清晰,更有效的代码。

背景 (Background)

One way to think about data types is to consider the different types of data that we use in the real world. An example of data in the real world are numbers: we may use whole numbers (0, 1, 2, …), integers (…, -1, 0, 1, …), and irrational numbers (π), for example.

考虑数据类型的一种方法是考虑现实世界中使用的不同数据类型。 现实世界中数据的一个示例是数字:例如,我们可以使用整数(0,1,2,…),整数(…,-1,0,1,…)和无理数(π)。

Usually, in math, we can combine numbers from different types, and get some kind of an answer. We may want to add 5 to π, for example:

通常,在数学中,我们可以组合不同类型的数字,并获得某种答案。 我们可能要在π上加5,例如:

5 + π

We can either keep the equation as the answer to account for the irrational number, or round π to a number with an abbreviated number of decimal places, and then add the numbers together:

我们可以保留方程作为解决无理数的答案,也可以将π舍入到小数位数后的数字,然后将这些数字加在一起:

5 + π = 5 + 3.14 = 8.14

But, if we start to try to evaluate numbers with another data type, such as words, things start to make less sense. How would we solve for the following equation?

但是,如果我们开始尝试使用其他数据类型(例如单词)来评估数字,那么事情就变得没有意义了。 我们如何求解以下方程式?

shark + 8

For computers, each data type is quite different—like words and numbers. As a result we have to be careful about how we use varying data types to assign values and how we manipulate them through operations.

对于计算机,每种数据类型都非常不同,例如单词和数字。 结果,我们必须注意如何使用不同的数据类型分配值以及如何通过操作来操纵它们。

整数 (Integers)

Like in math, integers in computer programming are whole numbers that can be positive, negative, or 0 (…, -1, 0, 1, …). In Go, an integer is known as an int. As with other programming languages, you should not use commas in numbers of four digits or more, so when you write 1,000 in your program, write it as 1000.

就像在数学中一样,计算机编程中的整数是可以为正,负或0(…,-1、0、1……)的整数 。 在Go中,整数称为int 。 与其他编程语言一样,您不应使用四位数或更多的逗号,因此在程序中写入1,000时,应将其写入1000

We can print out an integer in a simple way like this:

我们可以像这样简单地打印出一个整数:

fmt.Println(-459)

   
Output
-459

Or, we can declare a variable, which in this case is a symbol of the number we are using or manipulating, like so:

或者,我们可以声明一个变量,在这种情况下,它是我们正在使用或操作的数字的符号,如下所示:

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

   
Output
-459

We can do math with integers in Go, too. In the following code block, we will use the := assignment operator to declare and instantiate the variable sum:

我们也可以在Go中使用整数进行数学运算。 在下面的代码块中,我们将使用:=赋值运算符来声明和实例化变量sum

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

   
Output
48

As the output shows, the mathematical operator - subtracted the integer 68 from 116, resulting in 48. You’ll learn more about variable declaration in the Declaring Data Types for Variables section.

由于输出所示,数学运算符-减去整数68116 ,产生48 。 您将在“ 声明变量的数据类型”部分中了解有关变量声明的更多信息。

Integers can be used in many ways within Go programs. As you continue to learn about Go, you’ll have a lot of opportunities to work with integers and build upon your knowledge of this data type.

整数可以在Go程序中以多种方式使用。 在继续学习Go的过程中,您将有很多使用整数的机会,并会基于您对这种数据类型的了解。

浮点数字 (Floating-Point Numbers)

A floating-point number or a float is used to represent real numbers that cannot be expressed as integers. Real numbers include all rational and irrational numbers, and because of this, floating-point numbers can contain a fractional part, such as 9.0 or -116.42. For the purposes of thinking of a float in a Go program, it is a number that contains a decimal point.

浮点数浮点数用于表示不能表示为整数的实数 。 实数包括所有有理数和无理数,因此,浮点数可以包含小数部分,例如9.0或-116.42。 为了考虑Go程序中的浮点数,它是一个包含小数点的数字。

Like we did with integers, we can print out a floating-point number in a simple way like this:

就像我们对整数所做的一样,我们可以通过以下简单方式打印出浮点数:

fmt.Println(-459.67)

   
Output
-459.67

We can also declare a variable that stands in for a float, like so:

我们还可以声明一个代表浮点数的变量,如下所示:

absoluteZero := -459.67
fmt.Println(absoluteZero)

   
Output
-459.67

Just like with integers, we can do math with floats in Go, too:

就像整数一样,我们也可以在Go中使用浮点数进行数学运算:

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

   
Output
929.24

With integers and floating-point numbers, it is important to keep in mind that 3 ≠ 3.0, as 3 refers to an integer while 3.0 refers to a float.

对于整数和浮点数,请务必牢记3≠3.0,因为3表示整数,而3.0表示浮点数。

数值类型的大小 (Sizes of Numeric Types)

In addition to the distinction between integers and floats, Go has two types of numeric data that are distinguished by the static or dynamic nature of their sizes. The first type is an architecture-independent type, which means that the size of the data in bits does not change, regardless of the machine that the code is running on.

除了区分整数和浮点数外,Go还具有两种类型的数值数据,它们的大小是静态的还是动态的。 第一种类型是与体系结构无关的类型,这意味着无论代码运行在哪台机器上,以位为单位的数据大小都不会改变。

Most system architectures today are either 32 bit or 64 bit. For instance, you may be developing for a modern Windows laptop, on which the operating system runs on a 64-bit architecture. However, if you are developing for a device like a fitness watch, you may be working with a 32-bit architecture. If you use an architecture-independent type like int32, regardless of the architecture you compile for, the type will have a constant size.

当今大多数系统架构是32位或64位。 例如,您可能正在开发现代Windows笔记本电脑,其操作系统在64位体系结构上运行。 但是,如果您是为健身手表等设备开发的,则可能正在使用32位架构。 如果使用int32类的与体系结构无关的类型,则不管您编译的体系结构如何,该类型的大小都将恒定。

The second type is an implementation-specific type. In this type, the bit size can vary based on the architecture the program is built on. For instance, if we use the int type, when Go compiles for a 32-bit architecture, the size of the data type will be 32 bits. If the program is compiled for a 64-bit architecture, the variable will be 64 bits in size.

第二种类型是特定实现的类型。 在这种类型中,位大小可以根据程序所基于的体系结构而变化。 例如,如果我们使用int类型,则当Go编译为32位体系结构时,数据类型的大小将为32位。 如果程序是为64位体系结构编译的,则变量的大小为64位。

In addition to data types having different sizes, types like integers also come in two basic types: signed and unsigned. An int8 is a signed integer, and can have a value from -128 to 127. A uint8 is an unsigned integer, and can only have a positive value of 0 to 255.

除了具有不同大小的数据类型外,诸如整数之类的类型也有两种基本类型: signedunsignedint8是有符号整数,并且值可以在-128到127之间uint8是无符号整数,并且只能是0到255的正值。

The ranges are based on the bit size. For binary data, 8 bits can represent a total of 256 different values. Because an int type needs to support both positive and negative values, an 8-bit integer (int8) will have a range of -128 to 127, for a total of 256 unique possible values.

范围基于位大小。 对于二进制数据,8位可以表示总共256个不同的值。 因为int类型需要同时支持正值和负值,所以8位整数( int8 )的范围为-128至127,总共有256个唯一的可能值。

Go has the following architecture-independent integer types:

Go具有以下与体系结构无关的整数类型:

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)

Floats and complex numbers also come in varying sizes:

浮点数和复数也有不同的大小:

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 a couple of alias number types, which assign useful names to specific data types:

还有几种别名数字类型,它们为特定的数据类型分配有用的名称:

byte        alias for uint8
rune        alias for int32

The purpose of the byte alias is to make it clear when your program is using bytes as a common computing measurement in character string elements, as opposed to small integers unrelated to the byte data measurement. Even though byte and uint8 are identical once the program is compiled, byte is often used to represent character data in numeric form, whereas uint8 is intended to be a number in your program.

byte别名的目的是使您的程序在将字节用作字符串元素中的常见计算度量时(与与字节数据度量无关的小整数)相对应,以使其更清楚。 即使byteuint8在程序编译后完全相同, byte也经常用于以数字形式表示字符数据,而uint8则是程序中的数字。

The rune alias is a bit different. Where byte and uint8 are exactly the same data, a rune can be a single byte or four bytes, a range determined by int32. A rune is used to represent a Unicode character, whereas only ASCII characters can be represented solely by an int32 data type.

rune别名有点不同。 在byteuint8是完全相同的数据的情况下, rune可以是一个字节或四个字节,范围由int32确定。 rune用于表示Unicode字符,而仅ASCII字符只能由int32数据类型表示。

In addition, Go has the following implementation-specific types:

此外,Go具有以下特定于实现的类型:

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

Implementation-specific types will have their size defined by the architecture the program is compiled for.

特定于实现的类型的大小将由要为其编译程序的体系结构定义。

选择数值数据类型 (Picking Numeric Data Types)

Picking the correct size usually has more to do with performance for the target architecture you are programming for than the size of the data you are working with. However, without needing to know the specific ramifications of performance for your program, you can follow some of these basic guidelines when first starting out.

通常,选择正确的大小与您要为其编程的目标体系结构的性能有关,而不是所处理的数据的大小。 但是,无需了解程序性能的具体影响,您可以在首次启动时遵循其中一些基本准则。

As discussed earlier in this article, there are architecture-independent types, and implementation-specific types. For integer data, it’s common in Go to use the implementation types like int or uint instead of int64 or uint64. This will typically result in the fastest processing speed for your target architecture. For instance, if you use an int64 and compile to a 32-bit architecture, it will take at least twice as much time to process those values as it takes additional CPU cycles to move the data across the architecture. If you used an int instead, the program would define it as a 32-bit size for a 32-bit architecture, and would be significantly faster to process.

如本文前面所讨论的,有独立于体系结构的类型和特定于实现的类型。 对于整数数据,在Go中通常使用intuint类的实现类型,而不是int64uint64 。 通常,这将为您的目标体系结构带来最快的处理速度。 例如,如果您使用int64并编译为32位体系结构,则处理这些值所需的时间至少是在体系结构中移动数据所需的额外CPU周期的两倍。 如果使用int代替,则程序会将其定义为32位体系结构的32位大小,并且处理速度将大大提高。

If you know you won’t exceed a specific size range, then picking an architecture-independent type can both increase speed and decrease memory usage. For example, if you know your data won’t exceed the value of 100, and will only be a positive number, then choosing a uint8 would make your program more efficient as it will require less memory.

如果您知道不会超出特定的大小范围,那么选择与体系结构无关的类型既可以提高速度,又可以减少内存使用。 例如,如果您知道数据不会超过100的值,并且只会是一个正数,那么选择uint8将使您的程序更高效,因为它将需要更少的内存。

Now that we have looked at some of the possible ranges for numeric data types, let’s look at what will happen if we exceed those ranges in our program.

现在,我们已经研究了数字数据类型的一些可能范围,让我们看一下如果超出程序中的那些范围,将会发生什么。

溢出与绕行 (Overflow vs. Wraparound)

Go has the potential to both overflow a number and wraparound a number when you try to store a value larger than the data type was designed to store, depending on if the value is calculated at compile time or at runtime. A compile time error happens when the program finds an error as it tries to build the program. A runtime error happens after the program is compiled, while it is actually executing.

当您尝试存储的值大于设计要存储的数据类型的值时,Go可能会溢出一个数字并环绕一个数字,具体取决于该值是在编译时还是在运行时计算的。 当程序在尝试构建程序时发现错误时,就会发生编译时错误。 在程序实际执行时,在编译程序后会发生运行时错误。

In the following example, we set maxUint32 to its maximum value:

在以下示例中,我们将maxUint32设置为其最大值:

package main

import "fmt"

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

It will compile and run with the following result:

它将编译并运行,并显示以下结果:


   
Output
4294967295

If we add 1 to the value at runtime, it will wraparound to 0:

如果我们在运行时将该值加1 ,它将环绕到0


   
Output
0

On the other hand, let’s change the program to add 1 to the variable when we assign it, before compile time:

另一方面,让我们将程序更改为在分配变量时将其加1 ,然后再进行编译:

package main

import "fmt"

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

}

At compile time, if the compiler can determine a value will be too large to hold in the data type specified, it will throw an overflow error. This means that the value calculated is too large for the data type you specified.

在编译时,如果编译器可以确定某个值太大而无法容纳在指定的数据类型中,则它将引发overflow错误。 这意味着对于您指定的数据类型,计算出的值太大。

Because the compiler can determine it will overflow the value, it will now throw an error:

因为编译器可以确定它将溢出值,所以现在将引发错误:


   
Output
prog.go:6:36: constant 4294967296 overflows uint32

Understanding the boundaries of your data will help you avoid potential bugs in your program in the future.

了解数据的边界将有助于您避免将来程序中的潜在错误。

Now that we have covered numeric types, let’s look at how to store boolean values.

既然我们已经介绍了数字类型,让我们看一下如何存储布尔值。

布尔值 (Booleans)

The boolean data type can be one of two values, either true or false, and is defined as bool when declaring it as a data type. Booleans are used to represent the truth values that are associated with the logic branch of mathematics, which informs algorithms in computer science.

布尔数据类型可以是两个值之一,即truefalse ,并且在将其声明为数据类型时定义为bool 。 布尔值用于表示与数学逻辑分支相关联的真值,该真值可为计算机科学中的算法提供信息。

The values true and false will always be with a lowercase t and f respectively, as they are pre-declared identifiers in Go.

truefalse始终始终分别使用小写的tf ,因为它们是Go中预先声明的标识符。

Many operations in math give us answers that evaluate to either true or false:

数学中的许多运算都会为我们提供答案,答案为真或假:

    • 500 > 100 true

      500> 100是
    • 1 > 5 false

      1> 5错误
    • 200 < 400 true

      200 <400真
    • 4 < 2 false

      4 <2错误
    • 5 = 5 true

      5 = 5是
    • 500 = 400 false

      500 = 400错误

Like with numbers, we can store a boolean value in a variable:

像数字一样,我们可以将布尔值存储在变量中:

myBool := 5 > 8

We can then print the boolean value with a call to the fmt.Println() function:

然后,我们可以通过调用fmt.Println()函数来打印布尔值:

fmt.Println(myBool)

Since 5 is not greater than 8, we will receive the following output:

由于5不大于8 ,我们将收到以下输出:


   
Output
false

As you write more programs in Go, you will become more familiar with how booleans work and how different functions and operations evaluating to either true or false can change the course of the program.

随着您在Go中编写更多程序,您将更加熟悉布尔值的工作方式以及评估为truefalse不同函数和操作如何改变程序的过程。

弦乐 (Strings)

A string is a sequence of one or more characters (letters, numbers, symbols) that can be either a constant or a variable. Strings exist within either back quotes ` or double quotes " in Go and have different characteristics depending on which quotes you use.

字符串是一个或多个字符(字母,数字,符号)的序列,可以是常数或变量。 字符串在Go中的反引号`或双引号"中都存在,并且根据您使用的引号而具有不同的特征。

If you use the back quotes, you are creating a raw string literal. If you use the double quotes, you are creating an interpreted string literal.

如果使用反引号,则将创建原始字符串文字。 如果使用双引号,则将创建一个解释的字符串文字。

原始字符串文字 (Raw String Literals)

Raw string literals are character sequences between back quotes, often called back ticks. Within the quotes, any character will appear just as it is displayed between the back quotes, except for the back quote character itself.

原始字符串文字是反引号之间的字符序列,通常称为反引号。 在引号内,任何字符都将与反引号之间的显示相同,但​​反引号字符本身除外。

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

   
Output
Say "hello" to Go!

Usually, backslashes are used to represent special characters in strings. For example, in an interpreted string, \n would represent a new line in a string. However, backslashes have no special meaning inside of raw string literals:

通常,反斜杠用于表示字符串中的特殊字符。 例如,在解释的字符串中, \n表示字符串中的新行。 但是,反斜杠在原始字符串文字内部没有特殊含义:

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

Because the backslash has no special meaning in a string literal, it will actually print out the value of \n instead of making a new line:

因为反斜杠在字符串文字中没有特殊含义,所以它实际上会打印出\n的值,而不用换行:


   
Output
Say "hello" to Go!\n

Raw string literals may also be used to create multiline strings:

原始字符串文字也可以用于创建多行字符串:

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 the preceding code blocks, the new lines were carried over literally from input to output.

在前面的代码块中,新行从字面上从输入传递到输出。

解释的字符串文字 (Interpreted String Literals)

Interpreted string literals are character sequences between double quotes, as in "bar". Within the quotes, any character may appear except newline and unescaped double quotes. To show double quotes in an interpreted string, you can use the backslash as an escape character, like so:

解释的字符串文字是双引号之间的字符序列,例如"bar" 。 在引号内,除换行符和未转义的双引号外,任何字符都可能出现。 要在解释的字符串中显示双引号,可以将反斜杠用作转义符,如下所示:

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

   
Output
Say "hello" to Go!

You will almost always use interpreted string literals because they allow for escape characters within them. For more on working with strings, check out An Introduction to Working with Strings in Go.

您几乎总是使用解释的字符串文字,因为它们允许在其中使用转义字符。 有关使用字符串的更多信息,请参阅《 Go中的使用字符串简介》

具有UTF-8字符的字符串 (Strings with UTF-8 Characters)

UTF-8 is an encoding scheme used to encode variable width characters into one to four bytes. Go supports UTF-8 characters out of the box, without any special setup, libaries, or packages. Roman characters such as the letter A can be represented by an ASCII value such as the number 65. However, with special characters such as an international character of , UTF-8 would be required. Go uses the rune alias type for UTF-8 data.

UTF-8是一种编码方案,用于将可变宽度的字符编码为一到四个字节。 Go支持开箱即用的UTF-8字符,没有任何特殊的设置,库或程序包。 罗马字母(如字母A可以由ASCII值(如数字65)表示。但是,对于特殊字符(如国际字符 ,将需要UTF-8。 Go对UTF-8数据使用rune别名类型。

a := "Hello, 世界"

You can use the range keyword in a for loop to index through any string in Go, even a UTF-8 string. for loops and range will be covered in more depth later in the series; for now, it’s important to know that we can use this to count the bytes in a given string:

您可以在for循环中使用range关键字来索引Go中的任何字符串,甚至是UTF-8字符串。 for循环和range将在本系列的后面部分更深入地介绍; 现在,重要的是要知道我们可以使用它来计算给定字符串中的字节数:

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))
}

In the above code block, we declared the variable a and assigned the value of Hello, 世界 to it. The text assigned has UTF-8 characters in it.

在上面的代码块中,我们声明了变量a并为其分配了Hello, 世界的值。 分配的文本中包含UTF-8字符。

We then used a standard for loop as well as the range keyword. In Go, the range keyword will index through a string returning one character at a time, as well as the byte index the character is at in the string.

然后,我们使用了标准的for循环以及range关键字。 在Go中, range关键字将索引一次返回一个字符的字符串,以及该字符在字符串中的字节索引。

Using the fmt.Printf function, we provided a format string of %d: %s\n. %d is the print verb for a digit (in this case an integer), and %s is the print verb for a string. We then provided the values of i, which is the current index of the for loop, and c, which is the current character in the for loop.

使用fmt.Printf函数,我们提供了%d: %s\n的格式字符串%d: %s\n%d是数字的打印动词(在这种情况下为整数), %s是字符串的打印动词。 然后,我们提供的值i ,这是的当前索引for环,和c ,这是当前字符中的for循环。

Finally, we printed the entire length of the variable a by using the builtin len function.

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

Earlier, we mentioned that a rune is an alias for int32 and can be made up of one to four bytes. The character takes three bytes to define and the index moves accordingly when ranging through the UTF-8 string. This is the reason that i is not sequential when it is printed out.

之前,我们提到过,符文是int32的别名,可以由一到四个字节组成。 字符需要三个字节来定义,并且在范围通过UTF-8字符串时,索引会相应移动。 这就是i在打印时不连续的原因。


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

As you can see, the length is longer than the number of times it took to range over the string.

如您所见,该长度比在字符串上进行覆盖所花费的次数长。

You won’t always be working with UTF-8 strings, but when you are, you’ll now understand why they are runes and not a single int32.

您将不会总是使用UTF-8字符串,但是当您使用UTF-8字符串时,现在您将了解为什么它们是符文而不是单个int32

声明变量的数据类型 (Declaring Data Types for Variables)

Now that you know about the different primitive data types, we will go over how to assign these types to variables in Go.

现在您了解了不同的原始数据类型,我们将介绍如何在Go中将这些类型分配给变量。

In Go, we can define a variable with the keyword var followed by the name of the variable and the data type desired.

在Go中,我们可以使用关键字var定义变量,后跟变量名称和所需的数据类型。

In the following example we will declare a variable called pi of type float64.

在下面的示例中,我们将声明一个名为float64类型的pi变量。

The keyword var is the first thing declared:

关键字var是声明的第一件事:

var pi float64

Followed by the name of our variable, pi:

后跟我们的变量pi的名称:

var pi float64

And finally the data type float64:

最后是数据类型float64

var pi float64

We can optionally specify an initial value as well, such as 3.14:

我们还可以选择指定一个初始值,例如3.14

var pi float64 = 3.14

Go is a statically typed language. Statically typed means that each statement in the program is checked at compile time. It also means that the data type is bound to the variable, whereas in dynamically linked languages, the data type is bound to the value.

Go是一种静态类型的语言。 静态类型表示在编译时检查程序中的每个语句。 这也意味着数据类型绑定到变量,而在动态链接的语言中,数据类型绑定到值。

For example, in Go, the type is declared when declaring a variable:

例如,在Go中,在声明变量时声明类型:

var pi float64 = 3.14
var week int = 7

Each of these variables could be a different data type if you declared them differently.

如果您以不同的方式声明它们,则每个变量可以是不同的数据类型。

This is different from a language like PHP, where the data type is associated to the value:

这与PHP之类的语言不同,在PHP中,数据类型与值相关联:

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

In the preceding code block, the first $s is a string because it is assigned the value "sammy", and the second is an integer because it has the value 123.

在前面的代码块中,第一个$s是字符串,因为为其分配了值"sammy" ,第二个$s是整数,因为其具有值123

Next, let’s look at more complex data types like arrays.

接下来,让我们看一下数组等更复杂的数据类型。

数组 (Arrays)

An array is an ordered sequence of elements. The capacity of an array is defined at creation time. Once an array has allocated its size, the size can no longer be changed. Because the size of an array is static, it means that it only allocates memory once. This makes arrays somewhat rigid to work with, but increases performance of your program. Because of this, arrays are typically used when optimizing programs. Slices, covered next, are more flexible, and constitute what you would think of as arrays in other languages.

数组是元素的有序序列。 阵列的容量是在创建时定义的。 数组分配大小后,就无法再更改大小。 因为数组的大小是静态的,所以这意味着它仅分配一次内存。 这使数组在某种程度上很难使用,但可以提高程序的性能。 因此,在优化程序时通常使用数组。 接下来介绍的slice更加灵活,可以构成其他语言中的数组。

Arrays are defined by declaring the size of the array, then the data type with the values defined between curly brackets { }.

数组是通过声明数组的大小,然后声明带有大括号{ }之间定义的值的数据类型来定义的。

An array of strings looks like this:

字符串数组如下所示:

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

We can store an array in a variable and print it out:

我们可以将数组存储在变量中并打印出来:

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

   
Output
[blue coral staghorn coral pillar coral]

As mentioned before, slices are similar to arrays, but are much more flexible. Let’s take a look at this mutable data type.

如前所述,切片类似于数组,但更加灵活。 让我们看一下这种可变数据类型。

切片 (Slices)

A slice is an ordered sequence of elements that can change in length. Slices can increase their size dynamically. When you add new items to a slice, if the slice does not have enough memory to store the new items, it will request more memory from the system as needed. Because a slice can be expanded to add more elements when needed, they are more commonly used than arrays.

切片是可以改变长度的元素的有序序列。 切片可以动态增加其大小。 当您将新项目添加到切片时,如果切片没有足够的内存来存储新项目,则它将根据需要从系统请求更多内存。 因为可以在需要时扩展切片以添加更多元素,所以它们比数组更常用。

Slices are defined by declaring the data type preceded by an opening and closing square bracket [] and having values between curly brackets { }.

切片通过声明数据类型来定义,该数据类型前面有一个方括号[]和一个开括号,并在大括号{ }之间具有值。

A slice of integers looks like this:

整数切片如下所示:

[]int{-3, -2, -1, 0, 1, 2, 3}

A slice of floats looks like this:

一片花车看起来像这样:

[]float64{3.14, 9.23, 111.11, 312.12, 1.05}

A slice of strings looks like this:

一片字符串看起来像这样:

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

Let’s define our slice of strings as seaCreatures:

让我们将字符串切片定义为seaCreatures

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

We can print them out by calling the variable:

我们可以通过调用变量将它们打印出来:

fmt.Println(seaCreatures)

The output will look exactly like the list that we created:

输出看起来与我们创建的列表完全一样:


   
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关键字将一个项目添加到切片中。 以下命令将添加的字符串值, seahorse与切片:

seaCreatures = append(seaCreatures, "seahorse")

You can verify it was added by printing it out:

您可以通过打印输出来验证它是否已添加:

fmt.Println(seaCreatures)

   
Output
[shark cuttlefish squid mantis shrimp seahorse]

As you can see, if you need to manage an unknown size of elements, a slice will be much more versatile than an array.

如您所见,如果您需要管理未知大小的元素,则切片将比数组具有更多的用途。

地图 (Maps)

The map is Go’s built-in hash or dictionary type. Maps use keys and values as a pair to store data. This is useful in programming to quickly look up values by an index, or in this case, a key. For instance, you may want to keep a map of users, indexed by their user ID. The key would be the user ID, and the user object would be the value. A map is constructed by using the keyword map followed by the key data type in square brackets [ ], followed by the value data type and the key value pairs in curly braces.

地图是Go的内置哈希或字典类型。 地图使用作为一对来存储数据。 这在编程时非常有用,可以通过索引(在这种情况下为键)快速查找值。 例如,您可能要保留一张用户地图,并按用户ID索引。 密钥将是用户ID,而用户对象将是值。 通过使用关键字map后跟方括号[ ]的键数据类型,后跟花括号的value数据类型和键值对来构造map

map[key]value{}

Typically used to hold data that are related, such as the information contained in an ID, a map looks like this:

映射通常用于保存相关数据,例如ID中包含的信息,如下所示:

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

You will notice that in addition to the curly braces, there are also colons throughout the map. The words to the left of the colons are the keys. Keys can be any comparable type in Go. Comparable types are primitive types like strings, ints, etc. A primitive type is defined by the language, and not built from combining any other types. While they can be user-defined types, it’s considered best practice to keep them simple to avoid programming errors. The keys in the dictionary above are: name, animal, color, and location.

您会注意到,除了花括号外,整个地图中还存在冒号。 冒号左边的单词是键。 键可以是Go中任何可比较的类型。 可比较类型是原始类型,例如stringsints等。原始类型由语言定义,而不是通过组合任何其他类型而构建的。 尽管它们可以是用户定义的类型,但是最好将它们保持简单以避免编程错误。 上面的词典中的键是: nameanimalcolorlocation

The words to the right of the colons are the values. Values can be comprised of any data type. The values in the dictionary above are: Sammy, shark, blue, and ocean.

冒号右边的单词是值。 值可以包含任何数据类型。 上面的词典中的值是: Sammysharkblueocean

Let’s store the map inside a variable and print it out:

让我们将地图存储在变量中并打印出来:

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]

If we want to isolate Sammy’s color, we can do so by calling sammy["color"]. Let’s print that out:

如果我们想隔离Sammy的颜色,可以通过调用sammy["color"] 。 让我们打印出来:

fmt.Println(sammy["color"])

   
Output
blue

As maps offer key-value pairs for storing data, they can be important elements in your Go program.

由于地图提供了用于存储数据的键值对,因此它们可以成为Go程序中的重要元素。

结论 (Conclusion)

At this point, you should have a better understanding of some of the major data types that are available for you to use in Go. Each of these data types will become important as you develop programming projects in the Go language.

此时,您应该对可以在Go中使用的一些主要数据类型有更好的了解。 当您使用Go语言开发编程项目时,每种数据类型都将变得非常重要。

Once you have a solid grasp of data types available to you in Go, you can learn How To Convert Data Types in order to change your data types according to the situation.

一旦掌握了Go中可用的数据类型,就可以学习如何转换数据类型 ,以便根据情况更改数据类型。

翻译自: https://www.digitalocean.com/community/tutorials/understanding-data-types-in-go

golang数据类型

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值