
本文将介绍如何在 Go 语言中将整型 (int) 和长整型 (long) 数据转换为字符串,并提供代码示例。重点讲解 strconv 包中的 Itoa 和 FormatInt 函数,帮助开发者在并发程序中构建包含数字和时间信息的字符串。
在 Go 语言中,直接将整型或长整型数据与字符串进行拼接是不允许的。我们需要使用 strconv 包提供的函数将这些数值类型转换为字符串,然后才能进行字符串拼接操作。
使用 strconv.Itoa 转换 int 类型
strconv.Itoa 函数可以将 int 类型的整数转换为对应的字符串表示形式。 它的函数签名如下:
func Itoa(i int) string
例如:
package main
import (
"fmt"
"strconv"
)
func main() {
number := 123
str := "The number is: " + strconv.Itoa(number)
fmt.Println(str) // Output: The number is: 123
}使用 strconv.FormatInt 转换 long 类型
对于长整型数据(在 Go 中通常使用 int64 表示),我们需要使用 strconv.FormatInt 函数。 它的函数签名如下:
func FormatInt(i int64, base int) string
其中,i 是要转换的 int64 类型的整数,base 是进制(例如,10 表示十进制,16 表示十六进制)。
本文档主要讲述的是JSON.NET 简单的使用;JSON.NET使用来将.NET中的对象转换为JSON字符串(序列化),或者将JSON字符串转换为.NET中已有类型的对象(反序列化?)。希望本文档会给有需要的朋友带来帮助;感兴趣的朋友可以过来看看
例如:
package main
import (
"fmt"
"strconv"
"time"
)
func main() {
nanoseconds := time.Now().UnixNano()
str := "Current time in nanoseconds: " + strconv.FormatInt(nanoseconds, 10)
fmt.Println(str)
}并发场景下的字符串构建
在并发程序中,我们经常需要在不同的 Goroutine 之间传递包含数字和时间信息的字符串。 结合以上两种转换方法,可以轻松实现:
package main
import (
"fmt"
"strconv"
"time"
)
func routine1(out chan<- string) {
for i := 0; i < 30; i++ {
currentTime := time.Now().UnixNano()
message := "Message " + strconv.Itoa(i) + " at time: " + strconv.FormatInt(currentTime, 10)
out <- message
time.Sleep(100 * time.Millisecond) // 模拟一些工作
}
close(out) // 关闭 channel,通知 routine2 结束
}
func routine2(in <-chan string) {
for str := range in {
fmt.Println(str)
}
}
func main() {
out := make(chan string)
go routine1(out)
go routine2(out)
// 等待 Goroutine 完成
time.Sleep(5 * time.Second)
}在这个例子中,routine1 循环 30 次,每次构建包含循环计数器和当前时间(纳秒)的字符串,并通过 channel 发送给 routine2。 routine2 接收并打印这些字符串。
注意事项:
- 在并发环境中,确保对共享变量的访问是安全的。 在这个例子中,channel 用于 Goroutine 之间的通信,保证了数据的同步和安全。
- time.Now().UnixNano() 返回的是 int64 类型的时间戳,需要使用 strconv.FormatInt 进行转换。
- 当不再需要向 channel 发送数据时,应该关闭 channel,以便接收方知道何时停止接收数据。
总结
通过 strconv.Itoa 和 strconv.FormatInt 函数,我们可以方便地将 int 和 int64 类型的数据转换为字符串,并在字符串拼接中使用。 在并发程序中,结合 channel 等同步机制,可以安全地构建和传递包含数字和时间信息的字符串。掌握这些技巧对于编写高效且可靠的 Go 程序至关重要。









