top | item 19220116

(no title)

twentythree | 7 years ago

> 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

discuss

order

samstokes|7 years ago

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

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

jpttsn|7 years ago

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

vorg|7 years ago

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)
    ...
  }

jimsmart|7 years ago

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").