When making a slice or map...
type myType []map[string]someType
v = make(myType, 1)
v[0] = make(map[string]someType)
https://play.golang.org/p/Af9b0n0ykT
... I always have to specify the type twice. Can make
not infer it?
This would be especially helpful when the type is an anonymous struct.
For example in Java the second mention of the type can be omitted:
HashMap<String, SomeType> v = new HashMap<>();
No, it's not possible. make
requires a type as its first argument, and there are only two ways to specify a type: either as a name (eg: myType
) or as a type literal (eg: []int
).
In principle, you can work around this using reflect
:
package main
import (
"fmt"
"reflect"
)
type someType struct{}
type myType []map[string]someType
func main() {
var v = make(myType, 1)
reflect.ValueOf(v).Index(0).Set(reflect.MakeMap(reflect.TypeOf(v).Elem()))
fmt.Println(v)
}
But this doesn't look like a good idea at all to me.
with type myType []map[string]someType
you define a slice of maps and it is different type
https://play.golang.org/p/rElNLx0H0S
package main
type someType int
type mymap map[string]someType
type myType []mymap
func main() {
v := make(myType, 1)
v[0] = make(mymap)
// HashMap<String, SomeType> v = new HashMap<>();
var _ mymap = make(mymap)
}
runs totally fine