Search code examples
stringgoembeddedi2c

Is an empty string `[]byte("")` serialized as `\0`


Our code base is Go and C++. I'm a C++ programmer, so I can sort of follow Go, but I don't understand it well.

We are an embedded shop and the Go folks are serializing a string and sending it on an I2C buffer. It appears an empty Go string is appended to the I2C transaction as \0, instead of "nothing".

Everything I've seen in Go documentation has only described how to test for it (i.e. str == "" or len(str) > 0), but doesn't appear to describe how it is serialized.

As a C++ programmer, \0 makes sense, because it is the null terminator for strings or even simply NULL, which would make sense to store in a variable. Can someone please confirm or deny this?


Solution

  • The Go Language does not specify how Go values are serialized. The encoders in the Go standard library serialize empty strings in different ways. The gob encoder omits empty strings. The JSON encoder writes empty strings as "" (unless told to omit the empty string).

    In memory string values do not have a null terminator.