Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

encoding/binary: Need more helpful error message when writing struct to a buffer rather than a short "invalid type XXX" #22860

Open
hallazzang opened this issue Nov 23, 2017 · 2 comments

Comments

Projects
None yet
4 participants
@hallazzang
Copy link
Contributor

commented Nov 23, 2017

What version of Go are you using (go version)?

go1.9.2

Does this issue reproduce with the latest release?

In my version of go, yes. And maybe yes for THE LATEST version: src/encoding/binary/binary.go:362

What operating system and processor architecture are you using (go env)?

GOOS="darwin", GOARCH="amd64"

What did you do?

I was writing a program that writes a struct to a binary stream in order to communicate between C and Go using C's struct. See this playground as an example: https://play.golang.org/p/KG3WyuCiTj

What did you expect to see?

Well, I wanted to see my encoded struct's byte stream, ...

What did you see instead?

... but what I saw was an un-intuitive error:

panic: binary.Write: invalid type *main.Person

goroutine 1 [running]:
main.main()
	/tmp/sandbox274417894/main.go:24 +0x180

At the first time, I was like 'Ah, too bad. I cannot write struct directly into a byte buffer. There must be another way!' And what I found was this SO answer: https://stackoverflow.com/a/23176640/7804714

So the problem was that I should provide fixed-size(not just int; int16, int32, ...) members for struct. But the error message itself didn't provide any evidence of what is going wrong.

In the documentation, it says:

Data must be a fixed-size value or a slice of fixed-size values, or a pointer to such data.

But this still doesn't give any idea for struct's case(maybe it does, but me, couldn't catch that). I think binary.Write: non fixed-size field of type *main.Person would be much better. How do others think?

@gopherbot

This comment has been minimized.

Copy link

commented May 14, 2018

Change https://golang.org/cl/113075 mentions this issue: encoding/binary : fix error message for Write

@iWdGo

This comment has been minimized.

Copy link
Contributor

commented May 14, 2018

Submitted fix provides a message referring to documented constraint

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.