blob: 0d349f0a97246af4c98460148aa1cc055010b51b (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
package argvpb
var Stdout *StringWriter // bash uses this to match strings
var Stderr *StringWriter // bash dumps this as "help" about application options
var Stddbg *StringWriter // argv writes it's internal debugging output here
// StringWriter is a custom type that implements the io.Writer interface
// for a string variable. It holds a pointer to the string it will write to.
type StringWriter struct {
s *string
}
// NewStringWriter creates a new StringWriter that writes to the provided string pointer.
func NewStringWriter(s *string) *StringWriter {
return &StringWriter{s: s}
}
// Write implements the io.Writer interface. It appends the byte slice `p`
// to the string pointed to by the StringWriter.
func (sw *StringWriter) Write(p []byte) (n int, err error) {
// Append the contents of the byte slice p to the string *sw.s
*sw.s += string(p)
return len(p), nil
}
/*
func main() {
// 1. Declare the string variable that will be our output destination.
var myout string
// 2. Create a new writer that points to our string variable.
// Our StringWriter now satisfies the io.Writer interface.
writer := NewStringWriter(&myout)
// 3. Use our writer with functions that accept an io.Writer.
fmt.Fprintln(writer, "Hello, world!")
io.WriteString(writer, "This is the second line.\n")
fmt.Fprintf(writer, "A number: %d\n", 123)
// 4. Print the final contents of the string to verify.
fmt.Println("--- Final content of myout: ---")
fmt.Print(myout)
fmt.Println("-----------------------------")
}
*/
/*
package main
import (
"fmt"
"io"
"strings"
)
func main() {
// 1. Declare the final string variable.
var myout string
// 2. Create a strings.Builder. It already implements io.Writer.
var builder strings.Builder
// 3. Use the builder as the io.Writer.
fmt.Fprintln(&builder, "Hello from the builder!")
io.WriteString(&builder, "This is the second line.\n")
fmt.Fprintf(&builder, "Another number: %d\n", 456)
// 4. Get the final string from the builder and assign it.
myout = builder.String()
// 5. Print the final contents of the string to verify.
fmt.Println("--- Final content of myout: ---")
fmt.Print(myout)
fmt.Println("-----------------------------")
}
*/
|