Given a typedef of: "type ID int"
Is it possible to convert a map[ID]int to a map[int]int?
I've tried:
map[int]int(m)
as well as
m.(map[int]int)
and neither seems to work: http://play.golang.org/p/oPzkUcgyaR
Any advice?
Edit more details, since a couple people asked.
What I'm trying to do is score a league.
There are a bunch of "Teams", and each has a number of stats. For each stat, you get 10 points for being highest scoring, 9 for 2nd etc.
I modeled this as:
// Each team's statistics:
type StatLine map[StatID]float64
// The whole league:
map[TeamID]StatLine
// And I want to score that whole league with:
func score(s map[TeamID]StatLine) map[TeamID]int
// Only, is't also handy to score individual players:
func score(s map[PlayerID]StatLine) map[PlayerID]int
And it would be great not to write score() twice (since it's the same logic) or copy the whole map over.
It happens that PlayerID and TeamID are ints, hence I was curious if I could just write score(s map[int]int) and do type conversion. However, SteveMcQwark makes it clear why this might be a bad idea.
I think generics would solve this, but I know they're not immediately forthcoming. Any other ideas?
Thanks!
If you really want to do generics in Go, you need an interface. This interface will be implemented by two types, one for teams and one for players. The score function will take an object of this interface type as an argument and implement the common scoring logic without knowledge of whether it is working with teams or players. That's the overview. Here are some details:
The method set of the interface will be exactly the functions that the score function will need. Lets start with two methods it would seem to need,
type scoreable interface {
stats(scID) StatLine // get statLine for ID
score(scID, int) // set score for ID
}
and a generic scoreable ID type,
type scID int
The types that can implement this interface are not TeamID and PlayerID, but types that hold maps of them. Further, each of these types will need both maps, the StatLine and score maps. A struct works for this:
type teamScores struct {
stats map[TeamID]StatLine
scores map[TeamID]int
}
Implementing scoreable then,
func (s *teamScores) stats(id scID) StatLine {
return s.stats[TeamID(id)]
}
func (s *teamScores) score(id scID, sc int) {
s.scores[TeamID(id)] = sc
}
Wait, you might say. That type conversion of scID to TeamID. Is that safe? Had we might as well just go with the low-enginering approach of not even having TeamID? Well, it's safe as long as these methods are used sensibly. The struct teamScores associates a map of TeamIDs with another map of TeamIDs. Our soon-to-be-written generic function score takes this struct as an argument and thus is given the correct association. It cannot possibly mix up TeamIDs and PlayerIDs. That's valuable and in a large enough program can justify this technique.
Do the same for PlayerID, define a similar struct and add the two methods.
Write the score function once. Start like this:
func score(s scoreable) {
for
Oops, we need some way to iterate. An expedient solution would be to get a list of IDs. Let's add that method:
type scoreable interface {
ids() []scID // get list of all IDs
stats(scID) StatLine // get statLine for ID
score(scID, int) // set score for ID
}
and an implementation for teamScores:
func (s *teamScores) ids() (a []scID) {
for tid := range s.stats {
a = append(a, scID(tid))
}
return
}
Now where were we?
func score(s scoreable) {
// lets say we need some intermediate value
sum := make(map[scID]float64)
// for each id for which we have a statLine,
for _, id := range s.ids() { // note method call
// get the statLine
stats := s.stats() // method call
// compute intermediate value
sum[id] = 0.
for _, statValue := range stats {
sum[id] += statValue
}
}
// now compute the final scores
for id, s := range sum {
score := int(s) // stub computation
s.score(id, score) // method call
}
}
Notice the function takes the interface type scoreable, not pointer to interface like *scoreable. An interface can hold the pointer type *teamScores. No additional pointer to the interface is appropriate.
Finally, to call the generic function, we need an object of type teamScores. You probably already have the league stats, but might not have created the score map yet. You can do all this at once like this:
ts := &teamScores{
stats: ...your existing map[TeamID]Statline,
scores: make(map[TeamID]int),
}
call:
score(ts)
And the team scores will be in ts.scores.
The conversion rules are a tradeoff between expressiveness and maintainability. Whenever you convert between two types, you are making a gamble that those types will remain representationally and logically compatible in the future. One of the goals of the type system is to minimize the spread of dependency on this compatibility. On the other hand, it is very useful to be able to define multiple method sets that can operate on the same data, and conversions allow you to select the appropriate method set as needed to operate on existing data. You can only do conversions in cases where you could legitimately be swapping out method sets on otherwise identical types, which excludes the case you are asking about.
It might be useful to know what you're trying to do, rather than how you're trying to do it. I mean, you could wrap a map[ID]int
in a func(int)(int, bool)
if you just need read-only access to it, or you could use an interface { Get(int)(int, bool); Set(int, int); Delete(int) }
, but there's a good chance this is unnecessary.
It might be over-engineering to have separate types TeamID and PlayerID. If you used the same type for both, say ScoreableID, the problem would go away. In most cases, a variable name, function name, or the program context would make it clear whether something was a player or team. A comment would be appropriatiate in any remaining ambiguous code.