go.type_assertion_no_ok
Stability
Medium
Detects type assertions without the ok check.
Why It Matters
Section titled “Why It Matters”Type assertions without the ok check panic on failure:
- Runtime panics — Application crashes on unexpected types
- No graceful handling — No way to recover or provide fallback
- Hidden assumptions — Type expectations not visible in code
- Testing blind spots — Works until it receives unexpected data
A single unchecked type assertion can bring down your entire service.
Example
Section titled “Example”// ❌ Beforevalue := data.(string) // Panics if not stringIf data is anything other than a string, this panics.
// ✅ Aftervalue, ok := data.(string)if !ok { return errors.New("expected string")}Now you handle the error gracefully.
What Unfault Detects
Section titled “What Unfault Detects”- Type assertions without the second
okvalue - Interface type assertions without checking
- Type switches with fallthrough to assertion
Auto-Fix
Section titled “Auto-Fix”Unfault converts single-value assertions to two-value form with error handling.
Common Patterns
Section titled “Common Patterns”// Two-value assertion (safe)str, ok := v.(string)if !ok { return fmt.Errorf("expected string, got %T", v)}
// Type switch (safest for multiple types)switch v := data.(type) {case string: return processString(v)case int: return processInt(v)default: return fmt.Errorf("unexpected type: %T", v)}
// Assertion with default valuestr, ok := v.(string)if !ok { str = "default"}When Single-Value Is Safe
Section titled “When Single-Value Is Safe”// After a type check (still not recommended)if _, ok := v.(string); ok { str := v.(string) // Safe but redundant}
// Better: use type switchif str, ok := v.(string); ok { // Use str directly}