Fix Go "panic: interface conversion" — A String Asserted to Int, a Nil Interface, a Type That Does Not Implement the Target Interface, and a Typed Nil
A type assertion asked an interface value to be something it is not. Maybe a string asserted to int. Maybe a nil interface asserted to anything at all. Maybe a value asserted to an interface it does not implement, or a typed nil pointer taken for the value it points to. Below, each shape gets its own section: the exact output it prints, then the form that handles it as a value instead of a panic - the comma-ok assertion when you expect one type, a type switch when you expect several.
Written November 21, 2026 · Tested with Go 1.26.4 · 20 min read
- The first failure: a concrete type that does not match
- The nil interface: nothing stored at all
- The interface target: the dynamic type does not implement it
- The typed nil: an interface that is not nil and still holds no value
What this guide is
You hit panic: interface conversion when a type assertion guesses wrong.
Take x.(T). Here x has an interface type and T is the type you ask for. Go checks two things. First, is x non-nil? Second, does the value inside it fit T? If T is a concrete type, the stored value's dynamic type must be exactly T. If T is an interface, the stored type must implement it. Pass, and you get the stored value, typed as T. Fail, and the program panics right there.
Why doesn't the compiler stop you? Because it usually can't know what's inside. You declare an interface{}. At run time it might hold a string, an int, a pointer, nothing at all. The compiler knows T could legally sit in that interface, so it lets the code build. The run finds out.
An interface value is really a pair: the stored type plus the stored value. The declaration doesn't pin either one down. Think about where such values come from. JSON decoding. A map[string]interface{} shared between packages. A function that returns an interface because its callers pass different things. Somewhere upstream, code put a value in. The assertion is where you collect on that bet.
Read the panic message left to right, and don't reverse it. Go names the type that was actually stored first, then the type you asked for. Mix those up and you'll debug the wrong end.
The four shapes in this guide look alike in a stack trace. They aren't the same bug.
- A
stringwhere you expected anint? Bad data got in upstream. - A nil interface? Nothing got in at all.
- A value that lacks a method you asserted to? The type never promised that method. That's a contract problem.
- A typed nil pointer? Trickier. Your nil check passed, and there was still no value to use.
One case never reaches a panic. Suppose T is concrete and T doesn't implement the interface type of x. Then x could never hold a T in the first place. Go calls that assertion invalid and the compiler rejects it. No run, no panic. The panics below are the borderline ones — legal in principle, wrong on this particular run.
All examples use Go 1.26.4. Each one is a single main.go in one module. Make the module once, from an empty directory:
$ mkdir ifaceconv
$ cd ifaceconv
$ go mod init example.com/ifaceconv
go: creating new go.mod: module example.com/ifaceconv
After that, swap in each program as the new main.go. Transcripts come from go run -trimpath main.go. The -trimpath flag shortens file paths in the trace — you see ./main.go:7 instead of a long absolute path. Line numbers match either way. Tested with Go 1.26.4.
The first failure: a concrete type that does not match
Start small. Put a string in an empty interface. Assert it to int.
// main.go
package main
import "fmt"
func main() {
var x interface{} = "hello"
n := x.(int)
fmt.Println(n)
fmt.Println("after")
}
$ go run -trimpath main.go
panic: interface conversion: interface {} is string, not int
goroutine 1 [running]:
main.main()
./main.go:7 +0x28
exit status 2
Now read the first line slowly.
interface {} — that's the static type of x. is string — that's what's actually inside, the stored type. not int — that's what you asked for.
int isn't an interface, so Go wants identity. Is the stored type identical to int? No. It's string. Assertion false, panic, done. The fmt.Println("after") never runs.
Could the compiler have caught this one? In this toy, maybe you think so. In real code, no — an interface{} can hold an int, so the assertion isn't invalid. It just happens to hold the wrong thing today.
And in real code you won't see a literal "hello" one line above the crash. You'll see a number that arrived as text after decoding. Or a value another goroutine, another package, another version of the code put into a shared map. Or a return value from a function whose contract quietly changed last month. The assertion says "I expect an int." The stored value says otherwise. Go stops at the assertion, not at the spot where the string slipped in — which is why fixing this usually means tracing backwards.
The nil interface: nothing stored at all
Change one thing. Don't store anything.
// main.go
package main
import "fmt"
func main() {
var x interface{}
n := x.(int)
fmt.Println(n)
fmt.Println("after")
}
$ go run -trimpath main.go
panic: interface conversion: interface {} is nil, not int
goroutine 1 [running]:
main.main()
./main.go:7 +0x25
exit status 2
One word changed in the message: is nil instead of is string.
var x interface{} gives you an interface with no stored type and no stored value. Empty. The spec actually puts this check first in its wording: x.(T) asserts that x is not nil, before it says anything about types. There's no stored value whose type could match, so the assertion fails at step one.
That changes what you go looking for. Don't hunt for a wrong type here. Hunt for a missing step. Did an earlier function return early? Was an optional field never set? Did a branch that was supposed to fill x simply not run on this input?
You might hope the comma-ok form, covered below, separates "missing" from "wrong type." It doesn't. Both give you false and a zero value. If your code needs to know which one happened, test x == nil yourself, before you assert. ok tells you one thing only: did the assertion hold?
The interface target: the dynamic type does not implement it
T doesn't have to be concrete. Assert to an interface instead, and the failure reads differently.
// main.go
package main
import "fmt"
func main() {
var x interface{} = 42
s := x.(fmt.Stringer)
fmt.Println(s)
fmt.Println("after")
}
$ go run -trimpath main.go
panic: interface conversion: int is not fmt.Stringer: missing method String
goroutine 1 [running]:
main.main()
./main.go:7 +0x59
exit status 2
Here T is fmt.Stringer. It asks for one method: String() string.
Forget identity for this case. A stored type is never "identical" to an interface it satisfies, and Go doesn't ask for that. It asks: does the stored type implement T? The stored type is int. int has no String method. So no, it doesn't implement fmt.Stringer, and you get a panic that tells you exactly that — the stored type, target interface, and the missing method: missing method String.
Got an interface with three methods? Go names one missing method, not all of them. Fix that one, assert again, and you may meet the next missing method on the next run. The named method is a reason the assertion failed. It isn't a complete list.
Where does this show up outside toy programs? At registries and pipelines. You store values as interface{} in a registry. Later, some stage pulls one out and asserts it to the behavior it needs — say, something that can format itself. The stored value isn't broken. It isn't missing either. It's a perfectly good int that never signed up to be a Stringer. The pairing is wrong. Either the registry accepted a type it shouldn't have, or the assertion demands more than registered types were ever required to provide.
One fix is often to ask for less. Narrow the interface to the methods you actually call. More types satisfy a smaller interface, and sometimes that smaller interface is what you meant all along.
The typed nil: an interface that is not nil and still holds no value
This one fools people, because the obvious guard passes.
Store a nil *int in an interface. Is the interface nil? No.
// main.go
package main
import "fmt"
func main() {
var p *int
var x interface{} = p
fmt.Println(x == nil)
q, ok := x.(*int)
fmt.Println(q, ok, q == nil)
n := x.(int)
fmt.Println(n)
}
$ go run -trimpath main.go
false
<nil> true true
panic: interface conversion: interface {} is *int, not int
goroutine 1 [running]:
main.main()
./main.go:11 +0xc5
exit status 2
Walk the output in order.
x == nil prints false. Why? You assigned p, a typed nil pointer, to x. That assignment stored something: the stored type *int, paired with a nil value. A nil interface has neither part. This one has a type, so it isn't nil.
Next line: the comma-ok assertion to *int succeeds. It does — the stored type is exactly *int. You get back a nil *int, which prints as <nil>, with ok true and q == nil true.
Then x.(int) blows up. The stored type *int is not identical to int. The message says so plainly: interface {} is *int, not int.
Picture the production version. A function returns a typed nil pointer, wrapped in an interface, to signal "nothing here." The caller writes if result != nil, feels safe, and moves on. The check passed. Later the caller dereferences the pointer, or asserts to a different type, and that's where it dies — far from the return statement that caused it.
The root confusion is simple once you see it: == nil on an interface tests the pair, type and value together. It does not test the value alone. If typed nil values can cross a boundary in your code, check for them properly. Assert to the expected pointer type, then test the result for nil. Or fix the producer: return an untyped nil when there's no value. Pick one side of the boundary to own the check, and write it down in the contract.
The comma-ok form: the same question, answered as values
Every panic so far came from the single-value form. Go gives you a second form, and you should reach for it whenever failure is a normal possibility.
Write the assertion as v, ok := x.(T) in an assignment or initialization. If the assertion holds, ok is true and v is the stored value. If it fails, ok is false, v is the zero value for T, and — this is the point — no panic occurs.
One program runs three of the failing shapes through that form:
// main.go
package main
import "fmt"
func main() {
var x interface{} = "hello"
n, ok := x.(int)
fmt.Println(n, ok)
var y interface{}
m, ok2 := y.(int)
fmt.Println(m, ok2)
var z interface{} = 42
s, ok3 := z.(fmt.Stringer)
fmt.Println(s, ok3)
fmt.Println("after")
}
$ go run -trimpath main.go
0 false
0 false
<nil> false
after
Line by line:
The string asserted to int gives 0 false. That 0 is the zero value for int, not a converted string, not a parsed number. Just zero.
The nil interface asserted to int gives 0 false too. Same output, different cause. Keep that in mind: comma-ok collapses missing and wrong-typed into one answer.
The int asserted to fmt.Stringer gives <nil> false. <nil> is the zero value for an interface type.
And after prints. Nothing panicked.
So what's the real difference between the two forms? The single-value form says "this must hold, stop everything if it doesn't." The comma-ok form says "tell me whether it held, I'll decide what to do." Look at your own assertions with that lens. A lot of panics come from code that wrote a guarantee where the author actually had a question.
Two warnings, both worth taking seriously.
First, don't read v without checking ok. On failure v is a genuine value of type T — zero, but real. Code that ignores ok and uses v anyway has swapped a loud crash for a silent wrong answer flowing downstream. Read the pair together, in the branch, right at the assertion.
Second, ok is terse. False means "didn't hold." It won't tell you whether the value was nil, what type it was, or which method was missing. Need the reason? Ask separately — a nil test, or the type switch in the next section.
The type switch: one statement for several possible types
What if a value can legitimately be several types? You could chain comma-ok assertions: try int, try string, try... It works. It also gets ugly fast, and the handling code ends up buried under the probing code.
Use a type switch instead. The syntax looks like a type assertion, except the parentheses hold the keyword type. Each case names one stored type. Declare a variable in the switch expression and that variable takes the case's type inside each clause.
// main.go
package main
import "fmt"
func describe(x interface{}) {
switch v := x.(type) {
case int:
fmt.Println("int", v)
case string:
fmt.Println("string", v)
case nil:
fmt.Println("nil interface")
default:
fmt.Printf("other %T\n", v)
}
}
func main() {
describe(42)
describe("hello")
describe(nil)
describe(3.5)
fmt.Println("after")
}
$ go run -trimpath main.go
int 42
string hello
nil interface
other float64
after
Inside the int case, v is an int. Inside the string case, it's a string. No extra assertion, no cast.
Notice case nil. It catches the nil interface — precisely the shape comma-ok couldn't separate from a wrong type. If missing values need different handling from wrong-typed values in your code, this is your tool.
Anything unlisted lands in default, where v still has the interface type. That's why the program prints %T there. The last call passes 3.5, the switch has no float64 case, and the program reports other float64 and keeps going.
You can also put an interface type in a case. It matches any stored type that implements that interface. But watch the order. Cases are tested top to bottom, first match wins. Put a broad interface case above a concrete case and it will grab values the concrete case was written for, leaving that case dead.
When should you choose a switch over an interface? A switch fits a closed set: you know the types, the list rarely changes, each type gets its own handling. It fits badly when the set keeps growing. Every new type then means a new case in every switch in the codebase, and default quietly decides what unlisted types get — maybe not what you'd have chosen if you'd noticed. For an open set, define an interface with the methods your handlers need and assert to it once, with comma-ok. New types join by implementing the methods. No lists to update.
The fixed program
Here is a program that handles the shapes from this guide without panicking. A small comma-ok helper covers the single-type question. A type switch covers the multi-type question, with an interface case thrown in for values that carry a behavior.
// main.go
package main
import "fmt"
func asInt(x interface{}) (int, bool) {
n, ok := x.(int)
return n, ok
}
func describe(x interface{}) string {
switch v := x.(type) {
case int:
return fmt.Sprintf("int %d", v)
case string:
return fmt.Sprintf("string %q", v)
case fmt.Stringer:
return "Stringer " + v.String()
case nil:
return "no value"
default:
return fmt.Sprintf("other %T", v)
}
}
func main() {
fmt.Println(asInt("hello"))
fmt.Println(asInt(42))
var empty interface{}
fmt.Println(asInt(empty))
fmt.Println(asInt(42.0))
fmt.Println(describe("hello"))
fmt.Println(describe(42))
fmt.Println(describe(empty))
fmt.Println(describe(3.5))
}
$ go run main.go
0 false
42 true
0 false
0 false
string "hello"
int 42
no value
other float64
Check the eight results against the earlier panics.
asInt("hello") returns 0 false. That's the first panic in this guide, turned into values you can branch on.
asInt(42) returns 42 true. The one case where the single-value form would have worked too.
asInt(empty) — the nil interface — returns 0 false.
asInt(42.0) also returns 0 false, and this one surprises people. 42.0 equals 42 numerically, sure. But it's a float64, not an int, and the concrete-type rule is about type identity, not value equality. Assertions don't convert. If you want numeric conversion, write a conversion, in its own branch or case, where a reader can see it.
Now describe. The string and the int each get their own line. The nil interface gets no value — clearer than a bare false if that string ends up in a log. The unlisted float64 falls to default and gets reported by its stored type.
Nothing here calls recover. Nothing fakes a plausible value out of a wrong one. Each question is asked in a form that returns an answer, and the program prints the answer it got, including the answers that say "not what you hoped for."
One ordering note for describe: both a concrete case and an interface case appear in that switch, and the first matching case wins. A type that is listed concretely and also implements the interface case goes to whichever case comes first. So put concrete cases above interface cases — unless you deliberately want behavior to win over type.
The fixes, ranked
Use the comma-ok form wherever the assertion can fail in normal operation. Did the value come from decoding? From a map? From another component, or from user input? Then you don't control the type the value actually has, full stop. Write v, ok := x.(T), branch on ok, and keep the handling next to the assertion that produced it. This comes first because it's the smallest change that kills the panic at that site.
Use a type switch when more than one stored type is expected, or when nil needs its own handling. Comma-ok gives you one false for every failure. A switch separates them: a clause per expected type, the variable already typed for you, case nil for the missing value, default for everything else.
Keep the single-value form only where failure is a programming error you want to stop on. Some assertions really are invariants. A value your own function stored a line earlier. A type a constructor guarantees. There, a panic is a reasonable signal. Ask who controls the stored value. You, on every path? Keep the single-value form. Does any path lead outside your code? Then it isn't an invariant, whatever the original author assumed.
Fix the stored value at its source when the expectation is right. Sometimes the assertion states the correct contract and the value is just wrong. A decoder emits strings where numbers were promised. A registry accepts a type that lacks a required method. You could handle the failure at every assertion site, forever. Or fix the one place the bad value enters. The panic message names the stored type — follow it back.
Test interfaces for nil as a pair, not as a value. Say it again, because this bug recurs: an interface holding a typed nil pointer is not nil. A == nil check on the interface does not test the stored value. Assert to the expected type and test the result, or make the producer return an untyped nil.
Do not answer the panic by recovering around your own assertions, or by ignoring ok. A recover around code you own turns a missing check into an unwind, and the bad value will arrive again on the next call. Ignoring ok lets a zero value march on as if it were data. Both hide the problem instead of handling it. Handle the answer at the assertion.
Which fix for which cause
| What the message and code show | Cause | Fix |
|---|---|---|
interface conversion: interface {} is string, not int |
The stored type differs from the asserted concrete type | Use the comma-ok form and handle ok false, or a type switch if several types are valid |
interface conversion: interface {} is nil, not int |
The interface holds no value at all | Find why no value was stored; handle the missing case with a nil test or case nil in a type switch |
interface conversion: int is not fmt.Stringer: missing method String |
The stored type does not implement the asserted interface | Store a type that implements the interface, narrow the asserted interface, or test with the comma-ok form |
interface conversion: interface {} is *int, not int after a == nil check passed |
A typed nil pointer was stored in the interface | Assert to the pointer type and test the result for nil, or return an untyped nil at the producer |
No panic, and v, ok := x.(T) prints the zero value with false |
The comma-ok form answered a failing assertion as values | No fix needed at the assertion; handle the false branch as the design requires |
| A compile error that a type assertion is invalid because the asserted type cannot be stored | The asserted non-interface type does not implement the interface type of x |
Correct the types in the source; this case never reaches run time |
Checklist
- Read the panic text in order. After
is: the type of the value that was stored. Afternot: the type you asked for. In the interface form, the named missing method is the reason Go gives. - Go through your single-value assertions one by one. For each, name who controls the stored value. Any path from outside your code? Switch to comma-ok or a type switch.
- Use comma-ok? Then check that the code reads
okbefore trustingv, and that the false branch does something deliberate — not a fall-through carrying the zero value. - Need missing handled differently from wrong-typed? Test
x == nilbefore asserting, or give the type switch acase nilclause. - Audit boundaries that return interfaces. Can a typed nil pointer come back as a non-nil interface? Decide which side of the boundary owns that check.
- Assert to an interface? Check you aren't asking for methods you never call, and check that stored types were required to implement it where they are produced.
Related guides on this site
- Fix Go "Cannot Use ... As ..." Type Errors — Assignability, Conversions, and Untyped Constants — the compile-time side of Go's type rules. Those are the assignments and conversions the compiler rejects in source. This guide covers the opposite set: assertions the compiler lets through, settled at run time.
- Fix Go "panic: runtime error: invalid memory address or nil pointer dereference" — Nil Receivers, Returned Nil Pointers, and Typed Nil Interfaces — the panic that often comes next. A typed nil slips past an interface nil check, as in the fourth shape above, then fails later when something uses the nil pointer itself.
- Go Structs and Interfaces — Grouping Data and the Method Set That Defines Behavior — the method-set model behind the interface-target shape. A type implements an interface by having its methods, and that is what the
fmt.Stringerassertion in this guide tests at run time.
Sources
- The Go Programming Language, The Go Programming Language Specification — for type assertions (for
xof interface type and a typeT,x.(T)asserts thatxis not nil and that the value stored inxis of typeT; ifTis not an interface type the dynamic type ofxmust be identical toT, andTmust implement the interface type ofxor the assertion is invalid; ifTis an interface type the dynamic type ofxmust implementT; if the assertion holds the value of the expression is the value stored inxand its type isT; if the assertion is false a run-time panic occurs) and for the comma-ok form (an assertion in the formv, ok := x.(T)yields an additional untyped boolean value, true if the assertion holds, otherwise false withvset to the zero value for typeTand no run-time panic). - The Go Programming Language, Effective Go — for type switches (a type switch uses the syntax of a type assertion with the keyword
typeinside the parentheses to discover the dynamic type of an interface value; if the switch declares a variable in the expression, the variable has the corresponding type in each clause).
Keep Exploring
The full Go hub \u2014 slices and maps, concurrency, and the standard library.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.