🔧 Error Fixes
· 2 min read
Last updated on

Go: Cannot Use X as Type Y — How to Fix It


cannot use x (variable of type string) as type int in argument to processCount

What causes this

Go is strictly typed — there are no implicit type conversions. If a function expects an int and you pass a string, the compiler rejects it. Unlike JavaScript or Python, Go won’t try to convert types for you.

Common scenarios:

  • Passing a string to a function that expects a number
  • Mixing int and int64 (they’re different types in Go)
  • Using the wrong type from a JSON unmarshal
  • Interface type mismatches
  • Returning the wrong type from a function

Fix 1: Convert between string and number

import "strconv"

// String to int
count := "42"
num, err := strconv.Atoi(count)
if err != nil {
    log.Fatal(err)
}
processCount(num)

// Int to string
s := strconv.Itoa(42)

// String to float
f, err := strconv.ParseFloat("3.14", 64)

Fix 2: Convert between numeric types

Go doesn’t auto-convert between int, int32, int64, float64, etc.:

var x int = 42
var y int64 = int64(x)    // int → int64
var z float64 = float64(x) // int → float64
var w int = int(z)          // float64 → int (truncates)

Fix 3: Check the function signature

// If the function expects a specific type:
func processCount(n int64) { ... }

// ❌ int != int64
var count int = 42
processCount(count)

// ✅ Convert explicitly
processCount(int64(count))

Fix 4: Fix interface type assertions

var data interface{} = "hello"

// ❌ Can't use interface{} as string directly
fmt.Println(data + " world")

// ✅ Type assertion
s, ok := data.(string)
if ok {
    fmt.Println(s + " world")
}

Fix 5: Fix JSON unmarshaling types

JSON numbers unmarshal to float64 by default:

var result map[string]interface{}
json.Unmarshal(data, &result)

// ❌ result["count"] is float64, not int
count := result["count"].(int)

// ✅ Convert from float64
count := int(result["count"].(float64))

// ✅ Better: unmarshal into a typed struct
type Response struct {
    Count int `json:"count"`
}
var resp Response
json.Unmarshal(data, &resp)

How to prevent it

  • Use typed structs for JSON instead of map[string]interface{}
  • Be explicit about numeric types — decide on int vs int64 early and be consistent
  • Use strconv for string/number conversions — don’t try to cast directly
  • Let your IDE show you function signatures so you pass the right types

Related: Go: Multiple-Value in Single-Value Context — How to Fix It

Related: Go: Runtime Error — Invalid Memory Address or Nil Pointer Dereference