How to bufio.Write with a length specified?

57 views
Skip to first unread message

Peng Yu

unread,
Jan 18, 2018, 6:05:19 PM1/18/18
to golang-nuts
Hi,

The following example shows how to write a byte slice to a buffer. But
what if I want only write a length shorter (say 2 instead of 5) than
the size of the slice. Is there a function that allows users to
specify the length to write? Thanks.

$ cat main.go
#!/usr/bin/env gorun
// vim: set noexpandtab tabstop=2:
package main

import (
"os"
"bufio"
"fmt"
)

func main() {
f := bufio.NewWriter(os.Stdout)
d := []byte{'s', 'o', 'm', 'e', '\n'}
n, err := f.Write(d)
f.Flush()
fmt.Printf("wrote %d bytes, error %q\n", n, err)
}

--
Regards,
Peng

Bruno Albuquerque

unread,
Jan 18, 2018, 6:11:22 PM1/18/18
to Peng Yu, golang-nuts
n, err := f.Write(d[:length]) ?

Where length is the amount of data you want to write.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Dan Kortschak

unread,
Jan 18, 2018, 6:13:31 PM1/18/18
to Peng Yu, golang-nuts
If you want to write a length shorter than the slice, make the slice
shorter. No, seriously...

n, err := f.Write(d[:2])

Peng Yu

unread,
Jan 18, 2018, 6:36:50 PM1/18/18
to Dan Kortschak, Bruno Albuquerque, golang-nuts
Dan & Bruno,

I didn't realize that it is as simple as that :) Thanks.

Does it involve any extra copy of the byte slice? Or f.Write literally
access the memory of d and only access 2 bytes of data for writing to
the buffer?
--
Regards,
Peng

Bruno Albuquerque

unread,
Jan 18, 2018, 6:57:12 PM1/18/18
to Peng Yu, Dan Kortschak, golang-nuts
It creates a new slice header, but the backing array is not copied.

Bruno Albuquerque

unread,
Jan 18, 2018, 6:57:29 PM1/18/18
to Peng Yu, Dan Kortschak, golang-nuts
Actually, it is even possible that not even a new slice header is created in this case, but I did not check.

Marvin Renich

unread,
Jan 18, 2018, 8:35:20 PM1/18/18
to golang-nuts
* Peng Yu <peng...@gmail.com> [180118 18:37]:
> Dan & Bruno,
>
> I didn't realize that it is as simple as that :) Thanks.
>
> Does it involve any extra copy of the byte slice? Or f.Write literally
> access the memory of d and only access 2 bytes of data for writing to
> the buffer?

The blog entry https://blog.golang.org/go-slices-usage-and-internals
will give you some good info about this.

...Marvin

Reply all
Reply to author
Forward
0 new messages