Go

Fix Go "Cannot Use ... As ..." Type Errors — Assignability, Conversions, and Untyped Constants

Most Go type errors arrive in a single sentence shape: the compiler names the value it was handed, describes what that value is, names the type the place requires, and names the place. Read in that order, the sentence is the whole diagnosis — it says which of the language's few assignability conditions failed, and each failed condition has its own fix. This guide reproduces the sentence in its common forms, states the rule that produces it, and separates the look-alike cases: constants that are checked by representability rather than by type, named types that share an underlying type and still refuse each other, and conversions that are legal but do something other than what their spelling suggests.

Written November 18, 2026 · Tested with Go 1.26.4 · 29 min read

By the end of this guide
  • The first error: a string constant where an int belongs
  • The second error: an int variable where a string belongs
  • One sentence, several places
  • The exact rule: assignability

What this guide is

Go is strict about which values may land in which places. A variable, a parameter, and a result each declare a type, and a value offered for one of those places is accepted only if it is assignable to that type — a short, closed list of conditions in the language definition. When none of the conditions holds, the compiler stops the build with one sentence: cannot use X as T value in some named place. The sentence looks terse, but it carries four facts at once — the value, a description of the value, the required type, and the place — and the description in the middle is the part that identifies which condition failed and therefore which fix applies. The examples here use Go 1.26.4. Every example lives in a single file named main.go inside one module, created once from an empty directory:

Terminal
$ mkdir types
$ cd types
$ go mod init example.com/types
go: creating new go.mod: module example.com/types

Each program that follows replaces the contents of that main.go. When a build fails, the compiler prints the module path as a header line above the error — # example.com/types here — and the position in each message points at the value expression that was refused, not at the variable or parameter that required the type.

The first error: a string constant where an int belongs

The smallest program that earns the message offers a string constant to an int variable:

Go
// main.go
package main

func main() {
    var n int = "42"
    _ = n
}
Terminal
$ go build
# example.com/types
./main.go:5:14: cannot use "42" (untyped string constant) as int value in variable declaration

Read the message in its parts, from left to right. The position, ./main.go:5:14, is the value: line 5 is the declaration, and column 14 is where "42" begins — not the variable n, which sits earlier on the same line. Then comes the value itself, printed as written: "42", quotes included. The parenthesis describes the value: untyped string constant — the literal has a kind, string, but no named type of its own yet. Then the requirement: as int value, the type the place demands. Last, the place: in variable declaration. The _ = n line under the declaration changes nothing about this error; it keeps the unused-variable error out of the way so the type error stands alone.

The practical content of the message is that the digits inside the quotes do not matter. "42" is a string, and a string is never assignable to an int, however numeric its contents look. There is no parsing step hidden in an assignment. Turning text that holds digits into the number it names is a conversion a program performs explicitly, with a parsing function — a different operation from anything in this guide, and the reason this error so often appears in code that reads numbers from input.

The second error: an int variable where a string belongs

The mirror program offers a variable instead of a constant, and the description in the middle of the sentence changes to match:

Go
// main.go
package main

func main() {
    n := 42
    var s string = n
    _ = s
}
Terminal
$ go build
# example.com/types
./main.go:6:17: cannot use n (variable of type int) as string value in variable declaration

Here the value is the name n, and its description is variable of type int — a typed value, not a constant. The sentence shape is identical; only the description differs, and that difference is the diagnostic habit this guide builds: the parenthetical says what kind of thing was offered, and each kind fails for its own reason and takes its own fix. A constant is judged by whether the target type can represent it. A variable is judged by its declared type, and its current contents — here, the very digits a reader expects to become text — play no part at all.

One sentence, several places

The final phrase of the message names the place, and the place varies with the shape of the code while everything before it stays the same. An assignment to a variable declared earlier reports in assignment:

Go
// main.go
package main

func main() {
    var n int
    n = "42"
    _ = n
}
Terminal
$ go build
# example.com/types
./main.go:6:6: cannot use "42" (untyped string constant) as int value in assignment

A value passed to a function reports the place as an argument, and names the function:

Go
// main.go
package main

func show(n int) {}

func main() {
    show("42")
}
Terminal
$ go build
# example.com/types
./main.go:7:7: cannot use "42" (untyped string constant) as int value in argument to show

A value in a return statement reports that place instead:

Go
// main.go
package main

func num() int {
    return "42"
}

func main() {
    _ = num()
}
Terminal
$ go build
# example.com/types
./main.go:5:9: cannot use "42" (untyped string constant) as int value in return statement

Three places, one check. Arguments are assigned to parameters and return values are assigned to results, so the same assignability rule guards all of them, and the closing phrase simply records which assignment-shaped place caught the mismatch. When this error appears in working code, that phrase is the fastest locator: it says whether the wrong value sits in a declaration, a later assignment, a call, or a return.

The description in the middle varies with the value's shape as well. A struct variable is described by its kind and its type:

Go
// main.go
package main

type Point struct{ X, Y int }

func main() {
    p := Point{1, 2}
    var n int = p
    _ = n
}
Terminal
$ go build
# example.com/types
./main.go:8:14: cannot use p (variable of struct type Point) as int value in variable declaration

The full inventory of descriptions this guide meets is short: untyped string constant, untyped int constant — with the constant's value added when the constant is written as an expression — untyped float constant, variable of type U, and the struct forms variable of struct type U and value of struct type U. Each one points at a different section of the rule, which the next section states whole.

The exact rule: assignability

The specification defines the relation directly. A value x of type V is assignable to a variable of type T when one of the following conditions applies:

  • V and T are identical.
  • V and T have identical underlying types, are not type parameters, and at least one of V or T is not a named type.
  • V and T are channel types with identical element types, V is a bidirectional channel, and at least one of V or T is not a named type.
  • T is an interface type, but not a type parameter, and x implements T.
  • x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type, but not a type parameter.
  • x is an untyped constant representable by a value of type T.

That list is the whole of it. There is no further condition for values that are close in size, equal in contents, or printed the same way, and every error in this guide is a case where all six conditions fail at once. The channel condition is the one most code meets least; its passing shape is a bidirectional channel offered where a send-only or receive-only channel of the same element type is required:

Go
// main.go
package main

import "fmt"

func main() {
    bi := make(chan int, 1)
    var sendOnly chan<- int = bi
    sendOnly <- 7
    fmt.Println(<-bi)
}
Terminal
$ go run main.go
7

chan<- int is a type literal, not a named type, so the pairing has its unnamed side; the element types are identical, and bi is bidirectional, so the assignment holds. The sections that follow take the remaining conditions in the order working code meets them: named types first, then constants, then the conversions that remain when no condition applies.

Two named types over one underlying type

The second condition is the one that surprises, because it contains its own exception. Two types can share an underlying type completely and still refuse each other's values — when both of them are named. Two temperature types, each defined over float64, are the standard shape:

Go
// main.go
package main

type Celsius float64
type Fahrenheit float64

func main() {
    var c Celsius = 20
    var f Fahrenheit = c
    _ = f
}
Terminal
$ go build
# example.com/types
./main.go:9:21: cannot use c (variable of float64 type Celsius) as Fahrenheit value in variable declaration

The description is worth reading closely: variable of float64 type Celsius names both the underlying type and the named type, in that order. The values are the same shape, the same size, and — at this point in the program — the same number, and none of that is a condition on the list. Celsius and Fahrenheit are not identical, both are named, neither is an interface, and c is a variable rather than a constant or nil, so no condition applies. That refusal is the purpose of named types: the name is a claim that the values mean different things, and the compiler holds the program to the claim.

The fix is an explicit conversion, which is the programmer stating, in code, that the reinterpretation is intended:

Go
// main.go
package main

import "fmt"

type Celsius float64
type Fahrenheit float64

func main() {
    var c Celsius = 20
    var f Fahrenheit = Fahrenheit(c)
    fmt.Println(f)
}
Terminal
$ go run main.go
20

The output is 20, unchanged as a number — a conversion between types with identical underlying types changes the type and not the representation. What changed is who takes responsibility: the assignment was refused because the program had not said the crossing was deliberate, and the conversion says it.

The same condition, read from the other side, explains which assignments between a named type and its underlying shape do pass: the ones where one side has no name. A composite literal has an unnamed type, so a value of a named slice type and a value of the plain slice type pass in both directions:

Go
// main.go
package main

import "fmt"

type Scores []int

func main() {
    var s Scores = []int{1, 2}
    var plain []int = s
    fmt.Println(s, plain)
}
Terminal
$ go run main.go
[1 2] [1 2]

The literal []int{1, 2} has type []int, which is not a named type, so it is assignable to Scores; and s, offered back to a []int variable, passes by the same condition from the other direction. The trap is assuming the predeclared types behave like unnamed types here. They do not: int is itself a named type, so an int variable and a variable of a named int-based type are two named types, and the assignment fails exactly as the temperature assignment did:

Go
// main.go
package main

type UserID int

func main() {
    n := 7
    var id UserID = n
    _ = id
}
Terminal
$ go build
# example.com/types
./main.go:8:18: cannot use n (variable of type int) as UserID value in variable declaration

So the working rule is narrower than "same underlying type is enough." It is: same underlying type, and at least one side written as a type literal rather than a name — a slice, map, struct, or function literal type, for instance — or an explicit conversion to cross between two names.

Untyped constants: judged by representability

Constants enter the rule through the last condition, and it judges them by a different standard from variables: not by a declared type, which an untyped constant does not have, but by whether a value of the target type can represent the constant. An untyped floating-point constant whose value is a whole number is representable by an integer type:

Go
// main.go
package main

import "fmt"

func main() {
    var n int = 3.0
    fmt.Println(n)
}
Terminal
$ go run main.go
3

The same shape with a fractional value fails, and the compiler appends the reason to the message as a suffix:

Go
// main.go
package main

func main() {
    var n int = 3.9
    _ = n
}
Terminal
$ go build
# example.com/types
./main.go:5:14: cannot use 3.9 (untyped float constant) as int value in variable declaration (truncated)

The description is untyped float constant, with no value in the parenthesis because the constant is written as a plain literal, and the suffix (truncated) states the representability failure in one word: 3.9 is not an integer value, and assigning it would silently discard the fraction. Constants are never truncated on assignment. A whole-number constant passes because nothing would be lost; a fractional one fails because something would be.

Kind still binds constants, even untyped ones. An untyped integer constant is not representable by a string type — the representable values of a string type are strings — and the refusal is the plain sentence again:

Go
// main.go
package main

func main() {
    var s string = 42
    _ = s
}
Terminal
$ go build
# example.com/types
./main.go:5:17: cannot use 42 (untyped int constant) as string value in variable declaration

Size binds them too. A constant of the right kind that does not fit in the target type fails with a different suffix:

Go
// main.go
package main

func main() {
    var n int8 = 300
    _ = n
}
Terminal
$ go build
# example.com/types
./main.go:5:15: cannot use 300 (untyped int constant) as int8 value in variable declaration (overflows)

When the constant is written as an expression rather than a literal, the description carries the constant's computed value as well:

Go
// main.go
package main

func main() {
    var n int32 = 1 << 40
    _ = n
}
Terminal
$ go build
# example.com/types
./main.go:5:16: cannot use 1 << 40 (untyped int constant 1099511627776) as int32 value in variable declaration (overflows)

The two suffixes are the whole constant diagnostic system: (truncated) means the value would lose a fraction, (overflows) means it would not fit. Both are properties of the constant and the target type alone, known at compile time, which is why constant failures are exact in a way variable conversions are not — a variable converted to a smaller type wraps or truncates at run time, while a constant that would do either is refused before the program exists.

No implicit conversion between typed numeric values

Once a value has a type, the constant conditions no longer apply to it, and Go performs no implicit conversion between numeric types at all — not even between two integer types that hold the same range on the machine at hand. On a 64-bit platform int is 64 bits wide, and an int64 variable is still not assignable to an int variable:

Go
// main.go
package main

func main() {
    var big int64 = 42
    var n int = big
    _ = n
}
Terminal
$ go build
# example.com/types
./main.go:6:14: cannot use big (variable of type int64) as int value in variable declaration

The types are not identical, both are named, and the underlying-types condition cannot help because the underlying types differ as types even where their widths coincide. A floating-point variable offered to an integer variable fails the same way:

Go
// main.go
package main

func main() {
    f := 3.9
    var n int = f
    _ = n
}
Terminal
$ go build
# example.com/types
./main.go:6:14: cannot use f (variable of type float64) as int value in variable declaration

In both cases the fix is the explicit conversion, and for variables — unlike constants — the conversion is defined to go through, with the specification's numeric rules deciding the result: converting a floating-point value to an integer discards the fraction, truncating toward zero, for negative values as well as positive ones:

Go
// main.go
package main

import "fmt"

func main() {
    f := -3.9
    g := 3.9
    fmt.Println(int(f), int(g))
    var big int64 = 42
    fmt.Println(int(big))
}
Terminal
$ go run main.go
-3 3
42

int(-3.9) computed from a variable is -3, not -4: the fraction is dropped, the value moves toward zero. Note the contrast with the constant section above — 3.9 the constant cannot be assigned to an int at all, while 3.9 held in a float64 variable converts freely and truncates. The constant rule protects a value the compiler knows exactly; the conversion rule governs values it does not, and the programmer's explicit int(...) is the statement that the loss is accepted.

Conversions: what they may do, and the string trap

Trap
A conversion is an expression of the form T(x), and it is legal only when the specification's convertibility conditions hold — chiefly, that the value is assignable to T, that the two types have identical underlying types, or that both types are numeric, or both complex, or that one side is a string and the other a slice of bytes or runes, or an integer offered to a string type. A conversion is not a cast in the C sense and not a general reinterpretation: there is no linguistic mechanism to convert between pointers and integers, and a pairing the conditions do not list is a compile error of its own. Numeric-to-numeric conversions are the everyday case, covered above. The string pairings are where conversions mislead.

Converting an integer to a string type is legal, and it does not produce the integer's digits. It produces the string holding the one rune whose code point is the integer:

Go
// main.go
package main

import "fmt"

func main() {
    fmt.Printf("%q %q\n", string(65), string(42))
}
Terminal
$ go run main.go
"A" "*"

string(65) is "A" and string(42) is "*", because 65 and 42 are being read as Unicode code points, not as decimal text. This is the single most misleading legal conversion in the language, and the toolchain says so itself: the program above compiles, and go vet flags the same conversion when its operand is a variable:

Go
// main.go
package main

import "fmt"

func main() {
    n := 65
    fmt.Println(string(n))
}
Terminal
$ go vet
main.go:8:14: conversion from int to string yields a string of one rune, not a string of digits

The vet message states the correct expectation in its second half: digits are a formatting operation, not a conversion. The functions that produce them are strconv.Itoa for an int on its own and the fmt package's formatting verbs for values in context:

Go
// main.go
package main

import (
    "fmt"
    "strconv"
)

func main() {
    fmt.Println(strconv.Itoa(42), fmt.Sprint(42))
}
Terminal
$ go run main.go
42 42

The remaining everyday string pairing is the honest one: a string and a slice of bytes convert in both directions, byte for byte:

Go
// main.go
package main

import "fmt"

func main() {
    b := []byte("hi")
    s := string(b)
    fmt.Println(s, []byte(s))
}
Terminal
$ go run main.go
hi [104 105]

The round trip preserves the contents exactly — "hi" as bytes is the pair 104 105, and converting that slice back yields the same string. This pairing, and the corresponding []rune pairing, are the conversions to reach for when a function requires the other representation; they change the container type and nothing about the data.

Slice invariance: []int is not []any

One refusal in this family looks wrong to programmers arriving from languages with covariant containers. Every int value can be assigned to a variable of type any, one by one, yet a slice of int cannot be used where a slice of any is required:

Go
// main.go
package main

func show(v []any) {}

func main() {
    nums := []int{1, 2}
    show(nums)
}
Terminal
$ go build
# example.com/types
./main.go:8:7: cannot use nums (variable of type []int) as []any value in argument to show

Run the rule over the pair and the refusal is mechanical. []int and []any are not identical types — slice types are identical only when their element types are identical, and int is not any. Their underlying types are themselves, so the underlying-types condition compares the same two non-identical types and fails. No other condition mentions slices. Assignability is a relation between the two whole types as written, not a relation that reaches inside a type and rechecks its parts, so the element-by-element compatibility of int and any never enters into it.

The fix follows from that reading: build the slice the parameter actually declares, converting element by element:

Go
// main.go
package main

import "fmt"

func show(v []any) {
    fmt.Println(v...)
}

func main() {
    nums := []int{1, 2}
    out := make([]any, len(nums))
    for i, n := range nums {
        out[i] = n
    }
    show(out)
}
Terminal
$ go run main.go
1 2

Each loop iteration performs the one assignment that is legal — a single int value into an any slot, by the interface condition — and the finished out is a genuine []any, not the original slice under another name. The copy is not ceremony: the two slice types are different types, and a program that needs both keeps both, or converts at the boundary where the []any is required.

Interface failures name the missing method

The interface condition produces the longest form of the message, because when it fails the compiler appends the reason after a colon. A struct type with no Speak method, offered where a Speaker is required, earns the extension in full:

Go
// main.go
package main

type Speaker interface {
    Speak() string
}

type Dog struct{}

func greet(s Speaker) {}

func main() {
    greet(Dog{})
}
Terminal
$ go build
# example.com/types
./main.go:13:8: cannot use Dog{} (value of struct type Dog) as Speaker value in argument to greet: Dog does not implement Speaker (missing method Speak)

The base sentence is the familiar one, with the literal described as value of struct type Dog. Everything after the colon is the failed condition stated plainly: the type does not implement the interface, and the parenthesis names the method whose absence decides it. The fixes are the two the message implies — give the type the method, or pass a value whose type already has it. Adding the method makes the original call site compile unchanged:

Go
// main.go
package main

import "fmt"

type Speaker interface {
    Speak() string
}

type Dog struct{}

func (d Dog) Speak() string { return "woof" }

func greet(s Speaker) {
    fmt.Println(s.Speak())
}

func main() {
    greet(Dog{})
}
Terminal
$ go run main.go
woof

The pointer-receiver case is the same failure with a sharper parenthesis. A method declared on *Cat belongs to the method set of *Cat, not of Cat, so a Cat value does not implement the interface even though the method exists in the file:

Go
// main.go
package main

type Speaker interface {
    Speak() string
}

type Cat struct{}

func (c *Cat) Speak() string { return "meow" }

func greet(s Speaker) {}

func main() {
    greet(Cat{})
}
Terminal
$ go build
# example.com/types
./main.go:15:8: cannot use Cat{} (value of struct type Cat) as Speaker value in argument to greet: Cat does not implement Speaker (method Speak has pointer receiver)

The parenthesis this time is (method Speak has pointer receiver), and it hands the fix to the reader: pass the pointer, whose method set does contain Speak:

Go
// main.go
package main

type Speaker interface {
    Speak() string
}

type Cat struct{}

func (c *Cat) Speak() string { return "meow" }

func greet(s Speaker) {}

func main() {
    c := Cat{}
    greet(&c)
}
Command
$ go build

The build succeeds with no output. Two interface failures, two different parentheses, two different fixes — add the missing method in the first case, change the value offered in the second. Reading past the colon is what separates them; the base sentence alone would suggest the same repair for both.

nil: assignable only where nil is a value

The nil condition is the shortest on the list and the easiest to overgeneralize. nil is assignable to pointer, function, slice, map, channel, and interface types — the types whose zero value is nil itself. Offered to an int, it is refused, and its message is the one form in this guide with no parenthetical description at all:

Go
// main.go
package main

func main() {
    var n int = nil
    _ = n
}
Terminal
$ go build
# example.com/types
./main.go:5:14: cannot use nil as int value in variable declaration

nil has no type of its own to describe, so the sentence names it bare. The passing side of the condition covers the reference-shaped types in one program:

Go
// main.go
package main

import "fmt"

func main() {
    var s []int = nil
    var m map[string]int = nil
    var p *int = nil
    var i any = nil
    fmt.Println(s == nil, m == nil, p == nil, i == nil)
}
Terminal
$ go run main.go
true true true true

Each declaration holds because its type is on the condition's list, and each comparison confirms the variable actually holds nil rather than an empty-but-real value. When the cannot use nil message appears, the fix is never a conversion — there is nothing to convert — but a decision about what the absence should be in a type that has no absence: a zero value plus a separate boolean, a pointer to the value, or a redesigned signature.

The fixes, ranked

Convert explicitly when the types are two names for one shape, or two numeric types. Fahrenheit(c), int(big), int(f), string(b), []byte(s) — the conversion states that the crossing is intended and applies the specification's rules for the result, including truncation toward zero for a floating-point variable converted to an integer. This is the default fix for most refusals between typed values.

Parse or format when the crossing is between text and numbers. A string holding digits is not a number and a number is not its digit string, in either direction, and no conversion bridges that gap in the digit sense: string(65) yields "A". Use a parsing function for text to numbers and strconv.Itoa or the fmt formatting verbs for numbers to text.

Copy element by element when a container type differs. A []int never becomes a []any by conversion of the slice or by assignment; build the target slice and assign each element, which is legal one value at a time under the interface condition.

Satisfy the interface, or offer the value that does. When the message continues past a colon, the parenthesis names the repair: add the missing method to the type, or — when it says the method has a pointer receiver — pass the pointer instead of the value.

Change the constant, or widen the target, when a suffix appears. (truncated) and (overflows) are compile-time facts about a constant and a type. Either the constant was written wrong, or the target type is too narrow for the values the program handles; no conversion of the constant expression repairs an overflow the type cannot hold.

Rethink nil. A cannot use nil refusal means the target type has no absent value. Reach for a pointer, a slice, a map, or an explicit presence flag, according to what the absence means in the program — not for a cast-like workaround, since none exists.

Which fix for which cause

What the code shows Cause Fix
An untyped string constant offered to a numeric variable (cannot use "42" ... as int value) Text is not a number, however numeric its contents; assignment performs no parsing Parse the text, or write the value without quotes if it was meant to be a number
A typed variable offered to an unrelated type (variable of type int as string) The variable's declared type is not assignable to the target; its contents are irrelevant Convert explicitly if a convertibility condition holds, or format/parse if the crossing is text and number
Two named types over one underlying type (Celsius as Fahrenheit, int variable as UserID) Both are named types, so the rule for identical underlying types fails Explicit conversion: Fahrenheit(c), UserID(n)
A named type and an unnamed literal type over one underlying type ([]int literal as Scores) Not an error — at least one side is not a named type, so the assignment holds in both directions Leave it; reach for a conversion only when a second named type enters
A fractional untyped constant offered to an integer type (3.9 ... (truncated)) The constant is not representable by the target; constants are never truncated on assignment Write a whole-number constant, use a floating-point target, or convert a variable holding it
An untyped constant too large for the target (300 ... as int8 ... (overflows)) The constant is outside the target type's range Correct the constant, or widen the target type to one that holds it
An int64 or float64 variable offered to an int (variable of type int64 as int) Go performs no implicit numeric conversion between typed values, even at equal width Explicit conversion: int(big), int(f) — accepting truncation toward zero in the floating-point case
string(n) producing one character, not digits Converting an integer to a string yields one rune, not digits — legal, and go vet flags it strconv.Itoa or fmt.Sprint for digit text
A slice offered as a slice of another element type ([]int as []any) Slice types with different element types are not identical, and assignability does not look inside the slice Build the target slice and assign element by element
An interface refusal with a colon (Dog does not implement Speaker) The offered type's method set lacks a required method Add the method, or pass a value of a type that has it
An interface refusal naming a pointer receiver ((method Speak has pointer receiver)) The method is in the method set of *T, not of T Pass &value instead of value
cannot use nil as int value The target type is not one of the pointer, function, slice, map, channel, or interface types nil is assignable to Model the absence with a pointer or reference type, or a zero value plus a presence flag

Checklist

  • Before changing anything, read the message in its four parts: the value, the parenthetical description, the required type, and the place. The description identifies which assignability condition failed, and the fix follows from that condition, not from the types alone.
  • Before converting, check whether both types are named. Two named types over one underlying type always need the conversion spelled out; a named type and a type literal over one underlying type assign directly.
  • Before assigning a constant, check representability rather than type: whole values only for integer targets, in range for sized targets. A (truncated) or (overflows) suffix is a fact about the constant, fixable only by changing the constant or the type.
  • Before expecting an implicit numeric conversion, stop: there is none between typed values, at any width. Every numeric crossing between variables is a written conversion.
  • Before writing string(n) for a number, check what is wanted: a rune string, which the conversion gives, or digit text, which strconv.Itoa and fmt.Sprint give and the conversion never does.
  • Before passing a slice to an []any parameter, build the []any first. Element compatibility does not lift to slice compatibility.
  • Before repairing an interface refusal, read past the colon. A missing method and a pointer-receiver method are different defects with different fixes, and the parenthesis says which one occurred.
  • Before assigning nil, check the target type against the short list — pointer, function, slice, map, channel, interface. Any other type needs the absence modeled some other way.

Sources

  • The Go Programming Language Specification — for assignability (a value of type V is assignable to a variable of type T when the types are identical; when they have identical underlying types, are not type parameters, and at least one is not a named type; when both are channel types with identical element types, the source is a bidirectional channel, and at least one is not a named type; when T is an interface type that is not a type parameter and the value implements it; when the value is nil and T is a pointer, function, slice, map, channel, or interface type but not a type parameter; and when the value is an untyped constant representable by a value of T), for representability (a constant is representable by a value of a type when it is in the set of values that type determines, or rounds to a floating-point type's precision without overflow, or has components representable by a complex type's component type), for type identity (a named type is always different from any other type, and slice types are identical only when their element types are identical), for conversions (a non-constant value is convertible when it is assignable to the target, when the two types have identical underlying types ignoring struct tags, in the pointer-base case the specification lists, when both types are integer or floating-point types, when both are complex types, when an integer or a slice of bytes or runes meets a string type, when a string meets a slice of bytes or runes, and in the slice-to-array cases; a constant is convertible when it is representable by the target), for numeric conversions (a floating-point value converted to an integer discards its fraction, truncating toward zero), and for method sets (the method set of a defined type consists of the methods declared with that receiver type, and the method set of a pointer to a defined type consists of the methods declared with either receiver).
  • Effective Go — for the conversions discussion: converting a value to a type with the same underlying shape is legal and, in the Sequence and []int example, the conversion does not create a new value but lets the existing value act under the new type, while other legal conversions, such as integer to floating point, do create a new value; and for interface conversions and type assertions as the companion mechanism that takes an interface value to a type in a switch case.

Keep Exploring