Dominic Zukiewicz
Dominic Zukiewicz

Reputation: 8464

Dynamically built formatting strings in Golang

I am attempting to create a formatting string dynamically in Go. The idea is that a map is created with the formatting types. Then a loop goes through them to output the various types.

The end result is to see how the formatting affects the output.

(I appreciate the example will produce the same output, but I would change f over time to other types)

Below is an example of this:

import (
    "fmt"
    "strings"
)

var formats = []string{"%f", "%v"}
var f float32 = 1 << 24

func main() {
    for format := range formats {
        // Generate formatting string here
        parts := "%q => " + format + "\n"
        fmt.Printf(parts, format, f)
    }
}

The compiler is complaining about a int() conversion at the parts: line:

at line 11, file ch3/floating_point.go cannot convert "%q => " to type int

at line 11, file ch3/floating_point.go invalid operation: "%q => " + format` (mismatched types string and int)

I have attempted joining strings, but no luck:

parts:= strings.Join([]string{"%q =>",format,"\n"), " ")
fmt.Printf(parts,format,f)

Also fmt.Fprintf isn't helping either:

for format := range formats {
      // Generate formatting string here
      parts := fmt.Fprintf("%q => " + format, format, f)
      fmt.Println(parts)
    }

Upvotes: 2

Views: 2451

Answers (2)

Vitalii Velikodnyi
Vitalii Velikodnyi

Reputation: 1382

See golang For and blank identifier

If you're looping over an array, slice, string, or map, or reading from a channel, a range clause can manage the loop.

for key, value := range oldMap {
    newMap[key] = value
}

Right way to range with array

for index, value := range formats {

if you want to skip index do

for _, value := range formats {

Upvotes: 1

helmbert
helmbert

Reputation: 38024

The issue is in your for format := range formats construct. Keep in mind that range formats will return two values: the actual value from the slice *and its index (which is the first value). So "%q => " + format + "\n" will actually try to concatenate "%s => " with the numeric iteration index.

If you want to iterate over the values contained in the slice, use the following loop for that:

for _, format := range formats {
    // ...
}

Upvotes: 5

Related Questions