I am fairly new to Go, could someone help me diagnose this problem.
type ValidationStatus struct {
Passed bool
Errors map[string]*ValidationError
}
// ...
status := ValidationStatus{Passed: true}
// ...
status.Passed = false
fmt.Println(reflect.TypeOf(typeField.Name)) // string
fmt.Println(reflect.TypeOf(validationError)) // *validation.ValidationError
status.Errors[typeField.Name] = validationError // Panic triggered here.
validationError
is defined in the validation package. This code is in the same file as the struct.
This is the first time I have hit an issue like this, I think I may be using the map incorrectly but then I don't understand why this wouldn't cause a compile error so maybe a type issue? Any pointers to solve this would be much appreciated.
You didn't tell us what the error message was!
A new, empty map value is made using the built-in function make, which takes the map type and an optional capacity hint as arguments:
make(map[string]int) make(map[string]int, 100)
For example,
status := ValidationStatus{Passed: true, Errors: make(map[string]*ValidationError)}
Your map is nil
. You simply need to initialize it. This is why most object initialization is hidden behind a function:
status := ValidationStatus{Passed: true, Errors: make(map[string]*ValidationError)}
..or, behind a function:
status := NewValidationStatus()
// ...
func NewValidationStatus() ValidationStatus {
return ValidationStatus{
Passed: true,
Errors: make(map[string]*ValidationError),
}
}