4thSpace
4thSpace

Reputation: 44352

How to print using indexes?

Is there a way to print using variable indexes?

fmt.Fprintf("%[1] %[2] %[3] %[4]", a, b, c, d)

I get errors about

string does not implement io.Writer

Using fmt.Println prints the variable indexes as a literal.

Upvotes: 1

Views: 2580

Answers (2)

peterSO
peterSO

Reputation: 166714

Package fmt

Explicit argument indexes:

In Printf, Sprintf, and Fprintf, the default behavior is for each formatting verb to format successive arguments passed in the call. However, the notation [n] immediately before the verb indicates that the nth one-indexed argument is to be formatted instead. The same notation before a '*' for a width or precision selects the argument index holding the value. After processing a bracketed expression [n], subsequent verbs will use arguments n+1, n+2, etc. unless otherwise directed.

For example,

fmt.Sprintf("%[2]d %[1]d\n", 11, 22)

will yield "22 11"

func Fprintf

func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)

Fprintf formats according to a format specifier and writes to w. It returns the number of bytes written and any write error encountered.

func Printf

func Printf(format string, a ...interface{}) (n int, err error)

Printf formats according to a format specifier and writes to standard output. It returns the number of bytes written and any write error encountered.

For Fprintf provide an io.Writeror use Printf. Also, add format 'verbs' to your format specifier. For example,

package main

import (
    "fmt"
    "os"
)

func main() {
    a, b, c, d := 1, 2, 3, 4
    fmt.Fprintf(os.Stdout, "%[1]d %[2]d %[3]d %[4]d\n", a, b, c, d)
    fmt.Printf("%[1]d %[2]d %[3]d %[4]d\n", a, b, c, d)
}

Output:

1 2 3 4
1 2 3 4

Upvotes: 9

RoninDev
RoninDev

Reputation: 5686

fmt.Fprintf has definition:
func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)
So you need to provide writer.

For indexing you can use format like this: "%[2]d %[1]d"

Upvotes: 2

Related Questions