go - 如何将 int32 unicode 转换为字符串

标签 go

我有一个函数,它以 int32 slice 格式逐行接收主机名列表。这是函数:

func HandlePipeList(targetsList []int32) {
    //Print output item by item
    for i := 0; i < len(targetsList); i++ {
        fmt.Printf("%c", targetsList[i])
    }
}

由于我使用 fmt 将它转换为 %c,它可以正常工作并正确打印主机名。 当我尝试将 targetList 作为字符串传递给另一个函数时,我的问题就出现了。我怎样才能对 targetList 进行相同的转换,以便这些行可以作为字符串传递? (strconv.Itoa 在这里不起作用)。

最佳答案

Go 中的 unicode 代码点是一个 rune。 Go type rune 是 Go type int32 的别名。


The Go Programming Language Specification

Numeric types

int32   the set of all signed 32-bit integers

rune    alias for int32

Conversions

Conversions to and from a string type

Converting a slice of runes to a string type yields a string that is the concatenation of the individual rune values converted to strings.


使用string 类型转换。例如,

package main

import (
    "fmt"
)

func main() {
    targetsList := []int32("Testing, testing, ...")

    str := string(targetsList)
    fmt.Println(str)
}

Playground :https://play.golang.org/p/d-s0uLFl9MG

输出:

Testing, testing, ...

引用:The Go Blog: Strings, bytes, runes and characters in Go

关于go - 如何将 int32 unicode 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54606960/

相关文章:

docker - 关于 Golang 编译器的 docker 容器内的系统架构

go - 错误 'zadd'命令的参数数目错误

go - golang中如何匹配两个接口(interface)

Go channel 没有死锁或锁定

csv - 需要在CSV中添加数据而不需要在数据中添加逗号

go - 为什么这个 golang 程序在使用带有 select 的 for 循环时卡在 Playground 上?

go - 为什么 $GOPATH 通常设置在 ~/.bashrc 和 ~/.bash_profile 而不是 ~/.profile 中?

go - 为什么我们要在 Go 中使用空白标识符?

golang 从控制台删除符号

unit-testing - 如何在 Go Test IntelliJ 中重复运行一个或一组测试