GoLang实例 - 将Int转换为String类型教程

437 阅读3分钟

在这篇博文中,我们将通过实例来学习Go语言中Int类型的字符串转换

在Golang中的int, String类型

在任何编程语言中,用户在文本字段中输入的任何内容都被认为是字符串,并作为*整数* *保存在数据库中。 *在某些情况下,我们需要将这个Integer转换为String。例如,整数包含数字167,将这个int转换为字符串 "167"。

字符串和int是Go语言中的原始数据类型。Int是一般的数据类型,用于保存数字值。字符串是一组用双引号括起来的字符。在Go语言中,编译器不会像Int到String的转换那样隐含地铸造原始转换。开发者需要写一段代码来处理这个问题。

感谢Golang的标准strconv包。strconv是Go标准中的一个包,它提供了String与其他数据类型的转换,如int、float和boolean。你可以查看我的其他文章,关于字符串到/从布尔型的转换

Golang将Int类型转换为字符串

使用strconv标准包,将Int转换为String非常容易。strconv包提供了各种实现。

在Go语言中,有3种方法可以将Integer类型转换为字符串。

  • strconv FormatInt函数
  • strconv Itoa函数
  • fmt sprintf格式示例

strconv FormatInt函数示例

strconv FormatInt()函数接收输入值--整数值和基数,并返回代表数字的字符串值。你可以查看strconv FormatInt 示例的完整帖子。

以下是该函数的语法

func FormatInt(input int64, base int) string  

该函数的参数

input - 要转换为字符串类型的实际数字

base - 基数,从2到36。

该函数的返回值

返回一个代表数字的字符串值

下面是FormatInt的一个完整例子

package main  
  
import (  
 "fmt"  
 "strconv"  
)  
  
func main() {  
 input := int64(58)  
 fmt.Printf("type=%T, output=%v\n", input, input)  
 s0 := strconv.FormatInt(input, 2)  
 fmt.Printf("type=%T, output=%v\n", s0, s0)  
 s1 := strconv.FormatInt(input, 10)  
 fmt.Printf("type=%T, output=%v\n", s1, s1)  
 s2 := strconv.FormatInt(input, 16)  
 fmt.Printf("type=%T, output=%v\n", s2, s2)  
}  
  

输出是

type=int64, output=58  
type=string, output=111010  
type=string, output=58  
type=string, output=3a  

strconv.Itoa函数示例

strconv.Itoa()函数是简单的FormInt形式,相当于FormatInt(int64(i), 10)函数。该函数接收一个整数值并返回字符串类型的值 以下是Itoa函数的语法

以下是一个完整的Itoa函数的例子

package main  
  
import (  
 "fmt"  
 "reflect"  
 "strconv"  
)  
  
func main() {  
 var input = 20  
 output := strconv.Itoa(input)  
 fmt.Println(output)  
 fmt.Println("Input type: ", reflect.TypeOf(input))  
 fmt.Println("Output type", reflect.TypeOf(output))  
  
}  

当上述程序被编译和执行时,其输出结果如下

A:\Golang\work>go run Test.go  
20  
Input type:  int  
Output type string  

fmt Sprintf函数示例

包fmt Sprintf()函数,它接受任何数值参数,并转换为字符串类型,最后返回。
下面是Sprintf()函数的语法

func Sprintf(format string, input ...interface{}) string 

它接受两个参数--格式化字符串与%v和输入--任何值

package main  
  
import (  
 "fmt"  
 "reflect"  
)  
  
func main() {  
 var input = 20  
 output := fmt.Sprintf("%v", input)  
 fmt.Println(output)  
 fmt.Println("Input type: ", reflect.TypeOf(input))  
 fmt.Println("Output type", reflect.TypeOf(output))  
  
}  

输出是

20  
Input type:  int  
Output type string