4 ms·
> 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 use
by twentythree 8y 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
- jpttsn 8y agoI’d call the former usersByID (if that’s what the string is)
- samstokes 8y agoHow about describing the intended use of the collections? E.g. var usersByUsername map[string]*User var usersToEmail []*User
- vorg 8y agoYou 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 8y agoPersonally 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").