Casting []byte to data struct

8,066 views
Skip to first unread message

Javier Pérez

unread,
Nov 13, 2009, 1:45:55 PM11/13/09
to golang-nuts
Hello,

I am trying to read registers from a file, but os.Read() require a []
byte parameter, and my data structure is similar to:
type Data struct {
id uint64;
name [100]byte;
telephone [100]byte;
}

How can I cast []byte to Data?

This is not valid:
var bs [100]byte;
var d *Data = &bs;

Error: cannot use &bs (type *[100]uint8) as type *Data

Any idea?

Thanks.

Regards,
Javier Pérez

Sverre Rabbelier

unread,
Nov 13, 2009, 2:32:55 PM11/13/09
to Javier Pérez, golang-nuts
Heya,

2009/11/13 Javier Pérez <javier....@gmail.com>:
> How can I cast []byte to Data?

You don't.

> This is not valid:
> var bs [100]byte;
> var d *Data = &bs;

How about:
var bs [100]byte;
var d *Data;
d.name = &bs;

Or somethign like that. What I mean is, you need to assign the value
to a specific field rather than casting it.

--
Cheers,

Sverre Rabbelier

Russ Cox

unread,
Nov 13, 2009, 2:49:05 PM11/13/09
to Javier Pérez, golang-nuts
> I am trying to read registers from a file, but os.Read() require a []
> byte parameter, and my data structure is similar to:
> type Data struct {
>    id uint64;
>    name [100]byte;
>    telephone [100]byte;
> }
>
> How can I cast []byte to Data?

You can't, mainly because it breaks the type system (what if one
of the struct fields were a pointer?) but also because it produces
non-portable code.

http://golang.org/pkg/encoding/binary/ will read binary data into
a struct as long as you tell it the endianness and the struct uses
only basic types like you have above.

You'd say

var myData Data;
binary.Read(os.Stdin, binary.LittleEndian, &myData);

Russ

Javier Pérez

unread,
Nov 13, 2009, 8:50:37 PM11/13/09
to r...@golang.org, golang-nuts
Thank you Russ,

I understand that I want to do is unsafe. But I need read and write, I mean, "cast" Data to []byte, and "cast" []byte to Data. I am trying to develop a database server with records.

I've solved it reading one to one every byte and creating the data, and vice versa, but I think there should be a more appropriate method. It isn't?

Regards,
Javier Pérez



2009/11/13 Russ Cox <r...@golang.org>

Russ Cox

unread,
Nov 13, 2009, 8:56:40 PM11/13/09
to Javier Pérez, golang-nuts
2009/11/13 Javier Pérez <javier....@gmail.com>:
> Thank you Russ,
> I understand that I want to do is unsafe. But I need read and write, I mean,
> "cast" Data to []byte, and "cast" []byte to Data. I am trying to develop a
> database server with records.
> I've solved it reading one to one every byte and creating the data, and vice
> versa, but I think there should be a more appropriate method. It isn't?

That's what binary.Read does. You can read from
bytes.NewBuffer(data) if you already have the bytes
in memory.

Russ
Reply all
Reply to author
Forward
0 new messages