I have
type DocId int
func foo(documents []String) {
for i := range documents {
id := DocId(i)
...
}
}
How do I get rid of the explicit conversion line? DocIds are meant to be the type that indexes individual documents.
What I want is more like:
func foo(documents []String) {
for id := range documents {
... // id gets used as the DocId that it damn well *IS*
}
}
Which gives me ‘invalid operation: … (mismatched types int and DocId)’ when I attempt to use the id from range as a DocId, even though DocId is an int.
Only untyped constant can be automatically converted in the right type.
You can find examples where the cast is not needed like in this thread, for untyped constant. From the specs:
But here,
rangeexplicitly assign iteration values to the corresponding iteration variables(i int, T a[i]), which makesiandint. (from spec “For statement“)For all the other case, an explicit cast is required.
The “Conversion” section of the specs doesn’t mention an “automatic” type conversion (as opposed to automatic interface conversion, which happens all the time:
interface{}).This thread adds