How to redirect formatted output to a custom writer in Go using fmt.Fprintf?

To redirect formatted output to a custom writer in Go using fmt.Fprintf, you can follow these steps:

  1. Create a struct that implements the io.Writer interface. This struct will be used to capture the formatted output.
type CustomWriter struct { output *bytes.Buffer } func (w *CustomWriter) Write(p []byte) (n int, err error) { return w.output.Write(p) }
  1. Initialize the CustomWriter struct and pass it to fmt.Fprintf as the destination for the formatted output.
func main() { writer := CustomWriter{ output: &bytes.Buffer{}, } fmt.Fprintf(&writer, "Hello, %s!", "World") // Get the formatted output from the CustomWriter output := writer.output.String() fmt.Println(output) }

In the above example, the CustomWriter captures the formatted output in a bytes.Buffer called output. The Write method of the CustomWriter satisfies the io.Writer interface, allowing us to pass it to fmt.Fprintf as the destination for the formatted output.

Finally, we can retrieve the formatted output by invoking the String method on the output buffer. In this case, it will output "Hello, World!" to the console.