Typed helper functions

The other, frequently seen pattern is a per-type helper function, ex. (Go playground):

  1. // PtrInt returns *i.
  2. func PtrInt(i int) *int {
  3. return &i
  4. }
  5. // PtrStr returns *s.
  6. func PtrStr(s string) *string {
  7. return &s
  8. }
  9. func main() {
  10. // Use the two helper functions that return pointers to their provided
  11. // values. Remember, this pattern must scale with the number of distinct,
  12. // defined types that need to be passed by pointer instead of value.
  13. print(request{
  14. host: PtrStr("local"),
  15. port: PtrInt(80),
  16. })
  17. }

This approach requires a new function, per type. Surely there must be a more elegant solution…


Next: A generic solution