To convert a set of floats to a set of strings in Go, you can use a map to store the string representations of the floats. This approach leverages the fact that maps in Go are inherently unique.
In this example,
floatSet
using a slice literal, which contains the float values 1.1
, 2.2
, and 3.3
.stringMap
where the keys are strings and values are boolean (since we're interested in uniqueness, not the value itself).floatSet
using a for
loop and convert each float to its string representation using the fmt.Sprintf
function. We then add this string to stringMap
with a dummy boolean value.stringMap
.fmt.Println
function.package main
import (
"fmt"
)
func main() {
floatSet := []float64{1.1, 2.2, 3.3}
stringMap := make(map[string]bool)
for _, f := range floatSet {
stringMap[fmt.Sprintf("%g", f)] = true
}
var stringSet []string
for key := range stringMap {
stringSet = append(stringSet, key)
}
fmt.Println(stringSet)
}
[1.1 2.2 3.3]
In this tutorial, we learned How to Convert a Set of Floats to a Set of Strings in Go language with well detailed examples.