4 ms·
My newest two gotchas: 1. Don't use private attributes for struct types if you ever want to serialize/encode them (exception: Mutex and Channel Attributes). Ju
by JepZ 9y ago
My newest two gotchas:
1. Don't use private attributes for struct types if you ever want to serialize/encode them (exception: Mutex and Channel Attributes). Just had to refactor a whole lot of code just, because I decided I wanted to save the struct to disc. Btw. the type itself can and probably should be private.
2. Don't use Pointers in map key structs. As nesting maps is a pain the simple solution is to use structs as keys. But if you do so please remember not to use any pointer fields within those structs. Again when you encode and decode maps with pointers within the key structs those pointers will bite you.
- maddyboo 9y agoRe: #1 - You can always make your type implement the marshal/unmarshal method(s) so that it knows how to [de]serialize itself.
- dantheman0207 9y agoThe private attributes thing has also but me in the ass...encode/decide functions won’t touch private variables and won’t throw an error if all variables in a struct are private. What kind of issues did you run into with pointers inside of a struct in a map?
- derivagral 9y agoNot GP: I'd guess if you briefly forget that pointers are memory values you'll run into some Fun when trying to re-create a struct and use it as a key.
- JepZ 9y agoIn my case it wasn't just that I used pointers which might work in some cases. Instead I used a pointer to a global variable containing a function reference (directly using a function reference was not possible as those are not 'compareable'). Therefore, whenever I started the programm the global variable had a different location and therefore it didn't macht the location it had when the file was saved (during an earlier execution).
- jerf 9y agoFor #1, the "internal" package magic name allows you to have "private public" types; types that are public in terms of what reflect thinks about them, but are private in the sense that external packages still can't get at them (which is the operational definition of "private" in Go) so it's safe to have all of their attributes be "public", i.e., start with capital letters. I often use the "internal" when I have a package with a lot of internal-only marshaling behaviors, so that the godoc for the package isn't made up of 80% internal implementation details and 20% payload. "As nesting maps is a pain" Spend a few years in Perl with its autovivication and it'll seem a lot less painful. However, this is just an observation, not an actual recommendation.