Skip to content

go.type_assertion_no_ok

Stability Medium

Detects type assertions without the ok check.

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.

// ❌ Before
value := data.(string) // Panics if not string

If data is anything other than a string, this panics.

// ✅ After
value, ok := data.(string)
if !ok {
return errors.New("expected string")
}

Now you handle the error gracefully.

  • Type assertions without the second ok value
  • Interface type assertions without checking
  • Type switches with fallthrough to assertion

Unfault converts single-value assertions to two-value form with error handling.

// 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 value
str, ok := v.(string)
if !ok {
str = "default"
}
// After a type check (still not recommended)
if _, ok := v.(string); ok {
str := v.(string) // Safe but redundant
}
// Better: use type switch
if str, ok := v.(string); ok {
// Use str directly
}