In the code below, write_commas
requires the buffer parameter to be a pointer. It works.
The alternative (ie. NOT using a pointer) results in blank output.
Why is it that passing the actual bytes.Buffer
fails to print anything? Or put another way, does passing the actual bytes.Buffer
create a copy and thus, the bytes get written to a buffer that nothing is reading?
package main
import (
"fmt"
"bytes"
)
func main() {
s := "1234567898"
fmt.Println(Comma(s))
}
func Comma(s string) string {
var buf bytes.Buffer // <-- bytes.Buffer declared here.
sbytes := []byte(s)
decimal := bytes.LastIndex(sbytes,[]byte("."))
if decimal > 0 {
whole_part := sbytes[:decimal]
write_commas(whole_part, &buf) // <-- Address
float_part := sbytes[decimal:len(sbytes)]
for i := len(float_part); i > 0; i-- {
buf.WriteByte(float_part[len(float_part)-i])
}
} else {.
write_commas(sbytes, &buf) // <-- Address
}
return buf.String()
}
func write_commas(byr []byte, buf *bytes.Buffer) { // <-- Why *bytes.Buffer?
for i := len(byr); i > 0; i-- {
buf.WriteByte(byte(byr[len(byr)-i]))
if i > 1 && (i-1) % 3 == 0 {
buf.WriteByte(',')
}
}
}