Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> 2.3. Don’t name your variables for their types

What's the best way to handle a situation where you use two different types for the same data? e.g.

  var usersMap map[string]*User
  var usersList []*User


How about describing the intended use of the collections? E.g.

    var usersByUsername map[string]*User
    var usersToEmail []*User


I’d call the former usersByID (if that’s what the string is)


You could use a struct with private fields, e.g.

  type Users struct{
    dict map[string]*User
    list []*User
  }
and attach methods to both access the data and coordinatedly update both forms, e.g.

  func (us *Users) byID(id string) *User { ... }
  func (us *Users) sortedByID() []*User { ... }
  func (us *Users) addUser(id string, nu *User) {
    dict[id] = nu
    list = append(list, nu)
    ...
  }


Personally I'd use usersByID and users - I nearly always name my maps thingsByKey, and my default is that a plural thing on its own is nearly always a list, so adding a suffix of List doesn't add anything much here for me (Cheney's "Don’t name your variables for their types").




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: