RockNinja
RockNinja

Reputation: 2309

Write to stdout without creating a buffer

Inside a loop I do some calculations and then I want to print a string value from a byte array, once the loop is done print a new line.

Using fmt.Print will allocate a buffer, but all I want to do is print the character to stdout. Is there a way to do that?

for i, i < size; i++ {
    b = a[i] + i * 10
    fmt.Print(string((b)))
}
fmt.Println()

Upvotes: 2

Views: 6550

Answers (2)

user142162
user142162

Reputation:

You can do this by simply writing to the os.Stdout file:

var buff [1]byte
for i, i < size; i++ {
    b = a[i] + i * 10
    buff[0] = b
    os.Stdout.Write(buff[:])
}
buff[0] = '\n'
os.Stdout.Write(buff[:])

Upvotes: 9

nos
nos

Reputation: 229058

You can use fmt.Printf instead of your fmt.Print(string((b))) like so:

 fmt.Printf("%c", b)

Upvotes: 1

Related Questions