2

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)
    }
0

2 Answers 2

5

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 {
    // ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

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 {

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.