Reputation: 87
I have a function that receives a list of hostnames , line by line, in an int32 slice format. This is the function:
func HandlePipeList(targetsList []int32) {
//Print output item by item
for i := 0; i < len(targetsList); i++ {
fmt.Printf("%c", targetsList[i])
}
}
Since I'm converting it to %c
with fmt, it works and prints the hostnames correctly.
My problem arises when I try to pass targetsList as a string to another function. How can I make the same convertion for targetsList so that the lines could be passed as string? (strconv.Itoa
didn't work here).
Upvotes: 0
Views: 818
Reputation: 166885
A unicode code point in Go is a rune
. Go type rune
is an alias for Go type int32
.
The Go Programming Language Specification
int32 the set of all signed 32-bit integers rune alias for int32
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.
Use a string
type conversion. For example,
package main
import (
"fmt"
)
func main() {
targetsList := []int32("Testing, testing, ...")
str := string(targetsList)
fmt.Println(str)
}
Playground: https://play.golang.org/p/d-s0uLFl9MG
Output:
Testing, testing, ...
Reference: The Go Blog: Strings, bytes, runes and characters in Go
Upvotes: 1
Reputation: 159865
The built-in rune type is just an alias for int32
, so this is the same problem as converting a []rune
to string
. You might use something like strings.Builder
(https://godoc.org/strings#Builder) to assemble the string:
func runesToString(l []int32) (string, error) {
b := strings.Builder{}
for _, n := range l {
_, err := b.WriteRune(n)
if err != nil {
return "", err
}
}
return b.String(), nil
}
https://play.golang.org/p/MEXzsamubp6 has a complete working example.
Upvotes: 0