js中转换数据类型_如何在Go中转换数据类型

js中转换数据类型

介绍 (Introduction)

In Go, data types are used to classify one particular type of data, determining the values that you can assign to the type and the operations you can perform on it. When programming, there are times when you will need to convert values between types in order to manipulate values in a different way. For example, you may need to concatenate numeric values with strings, or represent decimal places in numbers that were initialized as integer values. User-generated data is often automatically assigned the string data type, even if it consists of numbers; in order to perform mathematical operations in this input, you would have to convert the string to a numeric data type.

在Go中,数据类型用于对一种特定类型的数据进行分类,确定可以分配给该类型的值以及可以对其执行的操作。 编程时,有时需要在类型之间转换值,以便以其他方式操作值。 例如,您可能需要将数字值与字符串连接起来,或在已初始化为整数值的数字中表示小数位。 用户生成的数据通常会自动分配为字符串数据类型,即使它由数字组成; 为了在此输入中执行数学运算,您必须将字符串转换为数字数据类型。

Since Go is a statically typed language, data types are bound to variables rather than values. This means that, if you define a variable as an int, it can only be an int; you can’t assign a string to it without converting the data type of the variable. The static nature of data types in Go places even more importance on learning the ways to convert them.

由于Go是一种静态类型的语言,因此数据类型绑定到变量而不是值。 这意味着,如果将变量定义为int ,则只能是int ; 您不能在不转换变量数据类型的情况下为其分配string 。 Go中数据类型的静态性质在学习转换它们的方式上更加重要。

This tutorial will guide you through converting numbers and strings, as well as provide examples to help familiarize yourself with different use cases.

本教程将指导您转换数字和字符串,并提供示例以帮助您熟悉不同的用例。

转换数字类型 (Converting Number Types)

Go has several numeric types to choose from. Primarily they break out into two general types: integers and floating-point numbers.

Go有几种数字类型可供选择。 首先,它们分为两种常规类型: 整数浮点数

There are many situations in which you may want to convert between numeric types. Converting between different sizes of numeric types can help optimize performance for specific kinds of system architecture. If you have an integer from another part of your code and want to do division on it, you may want to convert the integer to a float to preserve the precision of the operation. Additionally, working with time durations usually involves integer conversion. To address these situations, Go has built-in type conversions for most numeric types.

在许多情况下,您可能需要在数字类型之间进行转换。 在不同大小的数字类型之间进行转换可以帮助优化特定种类的系统体系结构的性能。 如果您有代码另一部分的整数,并且希望对其进行除法,则可能需要将整数转换为浮点数,以保持操作的精度。 此外,使用持续时间通常涉及整数转换。 为了解决这些情况,Go具有针对大多数数字类型的内置类型转换

在整数类型之间转换 (Converting Between Integer Types)

Go has many integer data types to pick from. When to use one over the other is typically more about performance; however, there will be times when you will need to convert from one integer type to another. For example, Go sometimes automatically generates numeric values as int, which may not match your input value. If your input value were int64, you would not be able to use the int and the int64 numbers in the same mathematical expression until you converted their data types to match.

Go有许多整数数据类型可供选择。 什么时候使用一个另一个通常是关于性能的 ; 但是,有时您需要从一种整数类型转换为另一种整数类型。 例如,Go有时会自动将数字值生成为int ,这可能与您的输入值不匹配。 如果您的输入值为int64 ,则在转换它们的数据类型以使其匹配之前,您将无法在同一数学表达式中使用intint64数字。

Assume that you have an int8 and you need to convert it to an int32. You can do this by wrapping it in the int32() type conversion:

假设您有一个int8并且需要将其转换为int32 。 您可以通过将其包装在int32()类型转换中来实现:

var index int8 = 15

var bigIndex int32

bigIndex = int32(index)

fmt.Println(bigIndex)

   
   
Output
15

This code block defines index as an int8 data type and bigIndex as an int32 data type. To store the value of index in bigIndex, it converts the data type to an int32. This is done by wrapping the int32() conversion around the index variable.

此代码块将index定义为int8数据类型,并将bigIndex定义为int32数据类型。 要将index的值存储在bigIndex ,它将数据类型转换为int32 。 这是通过将int32()转换包装在index变量周围来完成的。

To verify your data types, you could use the fmt.Printf statement and the %T verb with the following syntax:

要验证数据类型,可以使用fmt.Printf语句和具有以下语法的%T动词:

fmt.Printf("index data type:    %T\n", index)
fmt.Printf("bigIndex data type: %T\n", bigIndex)

   
   
Output
index data type: int8 bigIndex data type: int32

Since this uses the %T verb, the print statement outputs the type for the variable, and not the actual value of the variable. This way, you can confirm the converted data type.

由于此命令使用%T动词,因此print语句输出变量的类型,而不是变量的实际值。 这样,您可以确认转换后的数据类型。

You can also convert from a larger bit-size integer to a smaller bit-size integer:

您还可以将较大的位整数转换为较小的位整数:

var big int64 = 64

var little int8

little = int8(big)

fmt.Println(little)

   
   
Output
64

Keep in mind that when converting integers you could potentially exceed the maximum value of the data type and wraparound:

请记住,在转换整数时,您可能会超过数据类型和回绕的最大值:

var big int64 = 129
var little = int8(big)
fmt.Println(little)

   
   
Output
-127

A wraparound happens when the value is converted to a data type that is too small to hold it. In the preceding example, the 8-bit data type int8 did not have enough space to hold the 64-bit variable big. Care should always be taken when converting from a larger number data type to a smaller number data type so that you do not truncate the data by accident.

当值转换为太小而无法容纳的数据类型时,就会发生环绕。 在前面的示例中,8位数据类型int8没有足够的空间来容纳64位变量big 。 从较大数量的数据类型转换为较小数量的数据类型时,应始终小心,以免意外删除数据。

将整数转换为浮点数 (Converting Integers to Floats)

Converting integers to floats in Go is similar to converting one integer type to another. You can use the built-in type conversions by wrapping float64() or float32() around the integer you are converting:

在Go中将整数转换为浮点数类似于将一种整数类型转换为另一种整数类型。 您可以通过将float64()float32()包裹在要转换的整数周围来使用内置类型转换:

var x int64 = 57

var y float64 = float64(x)

fmt.Printf("%.2f\n", y)

   
   
Output
57.00

This code declares a variable x of type int64 and initializes its value to 57.

此代码声明类型为int64的变量x并将其值初始化为57

var x int64 = 57

Wrapping the float64() conversion around x will convert the value of 57 to a float value of 57.00.

float64()转换包装在x周围,​​会将57的值转换为57.00的float值。

var y float64 = float64(x)

The %.2f print verb tells fmt.Printf to format the float with two decimals.

%.2f打印动词告诉fmt.Printf将浮点数格式化为两位小数。

You can also use this process on a variable. The following code declares f as equal to 57, and then prints out the new float:

您还可以对变量使用此过程。 以下代码将f声明为等于57 ,然后打印出新的float:

var f float64 = 57
fmt.Printf("%.2f\n", f)

   
   
Output
57.00

By using either float32() or float64(), you can convert integers to floats. Next, you will learn how to convert floats to integers.

通过使用float32()float64() ,您可以将整数转换为浮点数。 接下来,您将学习如何将浮点数转换为整数。

将浮点数转换为整数 (Converting Floats to Integers)

Go can convert floats to integers, but the program will lose the precision of the float.

Go可以将浮点数转换为整数,但是程序将失去浮点数的精度。

Wrapping floats in int(), or one of its architecture-independent data types, works similarly to when you used it to convert from one integer type to another. You can add a floating-point number inside of the parentheses to convert it to an integer:

包装浮点数int()或与体系结构无关的数据类型之一,与使用它将一种整数类型转换为另一种整数类型时的工作原理相似。 您可以在括号内添加一个浮点数,以将其转换为整数:

var f float64 = 390.8
var i int = int(f)

fmt.Printf("f = %.2f\n", f)
fmt.Printf("i = %d\n", i)

   
   
Output
f = 390.80 i = 390

This syntax would convert the float 390.8 to the integer 390, dropping the decimal place.

此语法会将浮点数390.8转换为整数390 ,并390.8小数位。

You can also use this with variables. The following code declares b as equal to 125.0 and c as equal to 390.8, then prints them out as integers. Short variable declaration (:=) shortens up the syntax:

您也可以将其与变量一起使用。 以下代码将b声明为125.0 ,将c声明为390.8 ,然后将它们打印为整数。 简短的变量声明( := )缩短了语法:

b := 125.0
c := 390.8

fmt.Println(int(b))
fmt.Println(int(c))

   
   
Output
125 390

When converting floats to integers with the int() type, Go cuts off the decimal and remaining numbers of a float to create an integer. Note that, even though you may want to round 390.8 up to 391, Go will not do this through the int() type. Instead, it will drop the decimal.

当将int()类型的浮点数转换为整数时,Go会截断浮点数的小数和剩余数字以创建一个整数。 请注意,即使您可能希望将390.8舍入为391,Go也不会通过int()类型执行此操作。 相反,它将删除小数点。

数字转换为除法 (Numbers Converted Through Division)

When dividing integer types in Go the result will also be an integer type, with the modulus, or remainder, dropped:

当在Go中对整数类型进行除法时,结果也将是一个整数类型,其中的系数 (或余数)将被丢弃:

a := 5 / 2
fmt.Println(a)

   
   
Output
2

If, when dividing, any of the number types are a float, then all of the types will automatically be declared as a float:

如果除法时任何数字类型都是浮点数,那么所有这些类型将自动声明为浮点数:

a := 5.0 / 2
    fmt.Println(a)

   
   
Output
2.5

This divides the float 5.0 by the integer 2, and the answer 2.5 is a float that retains the decimal precision.

这会将浮点数5.0除以整数2 ,而答案2.5是保留小数精度的浮点数。

In this section, you have converted between different number data types, including differing sizes of integers and floating-point numbers. Next, you will learn how to convert between numbers and strings.

在本节中,您已在不同的数字数据类型之间进行转换,包括不同大小的整数和浮点数。 接下来,您将学习如何在数字和字符串之间转换。

用字符串转换 (Converting with Strings)

A string is a sequence of one or more characters (letters, numbers, or symbols). Strings are a common form of data in computer programs, and you may need to convert strings to numbers or numbers to strings fairly often, especially when you are taking in user-generated data.

字符串是一个或多个字符(字母,数字或符号)的序列。 字符串是计算机程序中数据的一种常见形式,您可能需要经常将字符串转换为数字或将数字转换为字符串,尤其是在接收用户生成的数据时。

将数字转换为字符串 (Converting Numbers to Strings)

You can convert numbers to strings by using the strconv.Itoa method from the strconv package in the Go standard libary. If you pass either a number or a variable into the parentheses of the method, that numeric value will be converted into a string value.

您可以使用Go标准库中strconv包中的strconv.Itoa方法将数字转换为字符串。 如果将数字或变量传递给方法的括号,则该数字值将转换为字符串值。

First, let’s look at converting integers. To convert the integer 12 to a string value, you can pass 12 into the strconv.Itoa method:

首先,让我们看一下转换整数。 要将整数12转换为字符串值,可以将12传递给strconv.Itoa方法:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    a := strconv.Itoa(12)
    fmt.Printf("%q\n", a)
}

When running this program, you’ll receive the following output:

运行此程序时,您将收到以下输出:


   
   
Output
"12"

The quotes around the number 12 signify that the number is no longer an integer but is now a string value.

数字12周围的引号表示该数字不再是整数,而是一个字符串值。

You used the := assignment operator to both declare a new variable with the name of a and assign the value returned from the strconv.Itoa() function. In this case, you assigned the value 12 to your variable. You also used the %q verb in the fmt.Printf function, which tells the function to quote the string provided.

您使用:=赋值运算符既可以声明一个名称为a的新变量,又可以分配从strconv.Itoa()函数返回的值。 在这种情况下,您将值12分配给了变量。 您还使用了fmt.Printf函数中的%q动词,该动词告诉该函数引用提供的字符串。

With variables you can begin to see how practical it can be to convert integers to strings. Say you want to keep track of a user’s daily programming progress and are inputting how many lines of code they write at a time. You would like to show this feedback to the user and will be printing out string and integer values at the same time:

使用变量,您可以开始了解将整数转换为字符串的实用性。 假设您想跟踪用户的日常编程进度,并输入他们一次编写多少行代码。 您想向用户显示此反馈,并将同时打印出字符串和整数值:

package main

import (
    "fmt"
)

func main() {
    user := "Sammy"
    lines := 50

    fmt.Println("Congratulations, " + user + "! You just wrote " + lines + " lines of code.")
}

When you run this code, you’ll receive the following error:

运行此代码时,您将收到以下错误:


   
   
Output
invalid operation: ("Congratulations, " + user + "! You just wrote ") + lines (mismatched types string and int)

You’re not able to concatenate strings and integers in Go, so you’ll have to convert the variable lines to be a string value:

您无法在Go中连接字符串和整数,因此必须将变量lines转换为字符串值:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    user := "Sammy"
    lines := 50

    fmt.Println("Congratulations, " + user + "! You just wrote " + strconv.Itoa(lines) + " lines of code.")
}

Now, when you run the code, you’ll receive the following output that congratulates your user on their progress:

现在,当您运行代码时,您将收到以下输出,祝贺您的用户的进度:


   
   
Output
Congratulations, Sammy! You just wrote 50 lines of code.

If you are looking to convert a float to a string rather than an integer to a string, you follow similar steps and format. When you pass a float into the fmt.Sprint method, from the fmt package in the Go standard library, a string value of the float will be returned. You can use either the float value itself or a variable:

如果要将浮点数转换为字符串,而不是将整数转换为字符串,请遵循类似的步骤和格式。 当您从Go标准库中的fmt包中将float传递到fmt.Sprint方法时,将返回float的字符串值。 您可以使用float值本身或变量:

package main

import (
    "fmt"
)

func main() {
    fmt.Println(fmt.Sprint(421.034))

    f := 5524.53
    fmt.Println(fmt.Sprint(f))
}

   
   
Output
421.034 5524.53

You can test to make sure it’s right by concatenating with a string:

您可以通过与字符串连接来测试以确保它是正确的:

package main

import (
    "fmt"
)

func main() {
    f := 5524.53
    fmt.Println("Sammy has " + fmt.Sprint(f) + " points.")
}

   
   
Output
Sammy has 5524.53 points.

You can be sure your float was properly converted to a string because the concatenation was performed without error.

您可以确定您的浮点数已正确转换为字符串,因为连接已正确执行。

将字符串转换为数字 (Converting Strings to Numbers)

Strings can be converted to numbers by using the strconv package in the Go standard library. The strconv package has functions for converting both integer and float number types. This is a very common operation when accepting input from the user. For example, if you had a program that asked for a person’s age, when they type the response in, it is captured as a string. You would then need to convert it to an int to do any math with it.

可以使用Go标准库中的strconv包将字符串转换为数字。 strconv软件包具有用于转换整数和浮点数类型的功能。 当接受来自用户的输入时,这是非常常见的操作。 例如,如果您有一个询问一个人年龄的程序,那么当他们键入响应时,它会被捕获为string 。 然后,您需要将其转换为int才能进行任何数学运算。

If your string does not have decimal places, you’ll most likely want to convert it to an integer by using the strconv.Atoi function. If you know you will use the number as a float, you would use strconv.ParseFloat.

如果字符串没有小数位,则很可能希望使用strconv.Atoi函数将其转换为整数。 如果您知道将数字用作浮点数,则可以使用strconv.ParseFloat

Let’s use the example of the user Sammy keeping track of lines of code written each day. You may want to manipulate those values with math to provide more interesting feedback for the user, but those values are currently stored in strings:

让我们以用户Sammy跟踪每天编写的代码行为例。 您可能希望通过数学操作这些值以为用户提供更多有趣的反馈,但是这些值当前存储在字符串中:

package main

import (
    "fmt"
)

func main() {
    lines_yesterday := "50"
    lines_today := "108"

    lines_more := lines_today - lines_yesterday

    fmt.Println(lines_more)
}

   
   
Output
invalid operation: lines_today - lines_yesterday (operator - not defined on string)

Because the two numeric values were stored in strings, you received an error. The operand - for subtraction is not a valid operand for two string values.

因为这两个数字值存储在字符串中,所以会收到错误消息。 操作数-减法不是两个字符串值有效的操作数。

Modify the code to include the strconv.Atoi() method that will convert the strings to integers, which will allow you to do math with values that were originally strings. Because there is a potential to fail when converting a string to an integer, you have to check for any errors. You can use an if statement to check if your conversion was successful.

修改代码以包含strconv.Atoi()方法,该方法会将字符串转换为整数,这将使您可以使用原始字符串的值进行数学运算。 由于将字符串转换为整数时可能会失败,因此必须检查是否有任何错误。 您可以使用if语句检查转换是否成功。

package main

import (
    "fmt"
    "log"
    "strconv"
)

func main() {
    lines_yesterday := "50"
    lines_today := "108"

    yesterday, err := strconv.Atoi(lines_yesterday)
    if err != nil {
        log.Fatal(err)
    }

    today, err := strconv.Atoi(lines_today)
    if err != nil {
        log.Fatal(err)
    }
    lines_more := today - yesterday

    fmt.Println(lines_more)
}

Because it is possible for a string to not be a number, the strconv.Atoi() method will return both the converted type, as well as a potential error. When converting from lines_yesterday with the strconv.Atoi function, you have to check the err return value to ensure that the value was converted. If the err is not nil, it means that strconv.Atoi was unable to successfully convert the string value to an integer. In this example, you used an if statement to check for the error, and if an error was returned, you used log.Fatal to log the error and exit the program.

因为字符串可能不是数字,所以strconv.Atoi()方法将返回转换后的类型以及潜在的错误。 使用strconv.Atoi函数从lines_yesterday进行转换时,必须检查err返回值以确保该值已转换。 如果err不是nil ,则表示strconv.Atoi无法成功将字符串值转换为整数。 在此示例中,您使用了if语句来检查错误,如果返回了错误,则使用log.Fatal记录错误并退出程序。

When you run the preceding code, you will get:

当您运行上述代码时,您将获得:


   
   
Output
58

Now try to convert a string that is not a number:

现在尝试转换不是数字的字符串:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    a := "not a number"
    b, err := strconv.Atoi(a)
    fmt.Println(b)
    fmt.Println(err)
}

You will get the following error:

您将收到以下错误:


   
   
Output
0 strconv.Atoi: parsing "not a number": invalid syntax

Because b was declared, but strconv.Atoi failed to make a conversion, a value was never assigned to b. Notice that b has the value of 0. This is because Go has default values, referred to as zero values in Go. strconv.Atoi provides an error describing why it failed to convert the string as well.

因为声明了b ,但是strconv.Atoi未能进行转换,所以从未将值分配给b 。 注意, b的值为0 。 这是因为Go具有默认值,在Go中称为零值。 strconv.Atoi提供了一个错误,描述了为什么它也未能转换字符串。

转换字符串和字节 (Converting Strings and Bytes)

Strings in Go are stored as a slice of bytes. In Go, you can convert between a slice of bytes and a string by wrapping it in the corresponding conversions of []byte() and string():

Go中的字符串存储为字节片。 在Go语言中,您可以通过在[]byte()string()的相应转换中进行包装来在字节的切片和字符串之间进行转换:

package main

import (
    "fmt"
)

func main() {
    a := "my string"

    b := []byte(a)

    c := string(b)

    fmt.Println(a)

    fmt.Println(b)

    fmt.Println(c)
}

Here you have stored a string value in a, then converted it to a slice of bytes b, then converted the slice of bytes back to a string as c. You then print a, b, and c to the screen:

在这里,您已将字符串值存储在a ,然后将其转换为字节片b ,然后将字节片转换回为c的字符串。 然后,将abc打印到屏幕上:


   
   
Output
my string [109 121 32 115 116 114 105 110 103] my string

The first line of output is the original string my string. The second line printed out is the byte slice that makes up the original string. The third line shows that the byte slice can be safely converted back into a string and printed back out.

输出的第一行是原始字符串my string 。 打印出的第二行是组成原始字符串的字节片。 第三行显示字节片可以安全地转换回字符串并重新打印出来。

结论 (Conclusion)

This Go tutorial demonstrated how to convert several of the important native data types to other data types, primarily through built-in methods. Being able to convert data types in Go will allow you to do things like accept user input and do math across different number types. Later on, when you are using Go to write programs that accept data from many different sources like databases and APIs, you will use these conversion methods to ensure you can act on your data. You will also be able to optimize storage by converting data to smaller data types.

该Go教程演示了如何主要通过内置方法将几种重要的本机数据类型转换为其他数据类型。 能够在Go中转换数据类型将使您能够执行诸如接受用户输入以及对不同数字类型进行数学运算之类的事情。 稍后,当您使用Go编写接受来自许多不同来源(如数据库和API)的数据的程序时,将使用这些转换方法来确保您可以对数据进行操作。 您还可以通过将数据转换为较小的数据类型来优化存储。

If you would like a deeper analysis of data types in Go, check out our Understanding Data Types in Go article.

如果您想对Go中的数据类型进行更深入的分析,请查看我们的理解Go中的数据类型文章。

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

js中转换数据类型

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值