Go Generics: A Real World Use Case
Until recently, I haven’t had many opportunities to use Go’s generics. I ran into a case where generics make sense. Best of all, this isn’t a contrived example. I’m working on a project and using openAPI to generate API contracts. One of the generated structs contains optional fields implemented as pointers. The only required field is Name. const ( Gzip PostPailsCompression = "gzip" None PostPailsCompression = "none" ) type PostPails struct { Compression *PostPailsCompression `json:"compression,omitempty"` // MaxArchiveSize Max size (bytes) before rotating to a new archive. MaxArchiveSize *int `json:"max_archive_size,omitempty"` // Name Name of the new pail Name string `json:"name"` } I need to populate the struct with values when writing unit tests. But dealing with pointers in Go test code usually results in using temporary variables. It’s not bad, but there’s some visual noise. ...