CodeGym /행동 /Go SELF /Interface value: (type, value)

Interface value: (type, value)

Go SELF
레벨 24, 레슨 1
사용 가능

1. What an interface value is

Usually a beginner wants to think of an interface as a “box” where you can put different types and then call methods, and that is all. That is a normal wish: the brain already has enough to deal with. But it is precisely because of this “box” that the most annoying bugs appear — when you checked err == nil, the logic went down the “no error” branch, and yet the program still behaves as if there was an error. Or the other way around: err != nil, but you print err and see <nil>, and you start suspecting that Go is trolling you.

The problem is not Go and not your luck. The problem is that an interface value consists of two parts. And nil for an interface is not the same as nil for a pointer.

Two parts of an interface: type and value

When we write var x error or var s fmt.Stringer, this is an interface variable. And in runtime it stores two things: which concrete type is inside and which concrete value of that type is inside.

You can think of it as a pair:

  • dynamic type (for example, *ValidationError)
  • dynamic value (for example, “such-and-such address”, or nil)

Important: the interface type (what is written on the left: error, Stringer, Greeter) is a contract. And the interface value (a variable of that type) is a container that remembers what is inside.

A convenient “picture in your head”:

interface value
+-----------------------------+
| dynamic type  | dynamic val |
+-----------------------------+

If a variable has neither type nor value, that is a “real nil interface”.

Three kinds of nil that people constantly mix up

Most often the confusion starts because the word nil is the same, but the situations are different. In Go it is especially important to distinguish a “nil pointer” from a “nil interface”.

Let us put this into a table:

Situation Example What is inside the interface == nil
Nil interface (the interface itself is empty)
var err error = nil
type: absent, value: absent
true
Nil pointer (ordinary pointer nil)
var p *T = nil
this is not an interface at all true (for p)
Typed nil in an interface (type exists, value is nil)
var p *T = nil; var err error = p
type: *T, value: nil false (for err)

And that third row is our main heroine. That is exactly typed nil: inside the interface there is nil, but “with a passport” (with a concrete type).

2. Demonstrations in code

Nil interface and %T

Now we will write a small piece of code that simply prints “what is inside”. We already know how to use fmt.Printf for diagnosing types and values — this is exactly the case where formatting is not decoration but a flashlight in a dark basement.

package main

import "fmt"

type Greeter interface {
	Greet() string
}

func main() {
	var g Greeter
	fmt.Println(g == nil) // true
	fmt.Printf("%T\n", g) // <nil>
}

Here g is a real nil interface: there is no dynamic type, and there is no value.

Typed nil: the interface is “not nil” even though inside it is nil

Now let us make the classic example: put a nil pointer inside an interface.

package main

import "fmt"

type Person struct {
	Name string
}

func (p *Person) String() string {
	if p == nil {
		return "<nil Person>"
	}
	return "Person(" + p.Name + ")"
}

func main() {
	var p *Person = nil

	var s fmt.Stringer = p
	fmt.Println(p == nil) // true
	fmt.Println(s == nil) // false

	fmt.Printf("%T %v\n", s, s) // *main.Person <nil Person>
}

Why is s == nil false? Because inside s a dynamic type *Person is stored. The value is nil, but the type exists. And the comparison iface == nil checks both parts at once: both the type and the value.

Notice the method String(): we made it “nil-safe” so printing is safe. This is not a required language rule, but a deliberate protection: if a method on a pointer receiver is called on nil, you need to be careful inside the method.

3. The error != nil trap

The most painful case: returning error

The most popular scenario where people step on typed nil is returning error. Because there is an implicit contract: nil error means success. And most of the code around Go relies on that: we keep comparing errors to nil.

Now imagine that you wrote your own error as a struct and return a pointer to it.

package main

import "fmt"

type ValidationError struct {
	Field string
	Msg   string
}

// Important: make the method nil-safe, otherwise printing/logging may panic.
func (e *ValidationError) Error() string {
	if e == nil {
		return "<nil ValidationError>"
	}
	return e.Field + ": " + e.Msg
}

func validateTitle(title string) error {
	if title == "" {
		return &ValidationError{Field: "title", Msg: "empty"}
	}

	var e *ValidationError = nil
	return e // DANGEROUS: typed nil wrapped in error
}

func main() {
	err := validateTitle("hello")
	fmt.Println(err == nil)        // false (and that is unexpected)
	fmt.Printf("%T %v\n", err, err) // *main.ValidationError <nil ValidationError>
}

If your inner voice is now saying “wait, but there is nil there!”, then you have caught the essence of the trap.

nil is the value of the pointer e, but what we return is the interface error. When it is wrapped, the interface gets the dynamic type *ValidationError, and the interface stops being nil.

The correct way: return a “real nil interface”

The fix is usually simple and a little… annoying: do not return the variable e if it is pointer-nil. You need to return exactly nil as error.

package main

type ValidationError struct {
	Field string
	Msg   string
}

func (e *ValidationError) Error() string {
	if e == nil {
		return "<nil ValidationError>"
	}
	return e.Field + ": " + e.Msg
}

func validateTitle(title string) error {
	if title == "" {
		return &ValidationError{Field: "title", Msg: "empty"}
	}
	return nil // IMPORTANT: nil interface, without a dynamic type
}

func main() {}

Here return nil creates an “empty” interface: without a dynamic type and without a value. And then err == nil will behave as expected.

4. Example: a task manager and a typed nil bug

To keep this from staying abstract, let us imagine that we are continuing a mini application for tasks (a hypothetical CLI task manager). We have a Task model and a function that creates a task and validates the input data.

In previous topics we already got used to keeping validation near the boundary (where we create the entity). Now it is important for us to make sure that the contract “nil = success” does not break.

Good variant: either an error or nil

package main

import "fmt"

type Task struct {
	Title string
}

type ValidationError struct {
	Field string
	Msg   string
}

func (e *ValidationError) Error() string {
	if e == nil {
		return "<nil ValidationError>"
	}
	return fmt.Sprintf("%s: %s", e.Field, e.Msg)
}

func NewTask(title string) (*Task, error) {
	if title == "" {
		return nil, &ValidationError{Field: "title", Msg: "empty"}
	}
	return &Task{Title: title}, nil
}

func main() {
	t, err := NewTask("buy milk")
	fmt.Println(t.Title, err == nil) // buy milk true
}

This is a good variant: we either return a concrete error, or we return nil as the error interface.

How it is easy to “break the contract” if you introduce an error variable

Now let us show how easy it is to ruin everything if you try to make the code “prettier” and introduce a variable for the error:

package main

type ValidationError struct {
	Field string
	Msg   string
}

func (e *ValidationError) Error() string {
	if e == nil {
		return "<nil ValidationError>"
	}
	return e.Field + ": " + e.Msg
}

func NewTask(title string) error {
	var verr *ValidationError

	if title == "" {
		verr = &ValidationError{Field: "title", Msg: "empty"}
	}

	return verr // typed nil, if title is not empty
}

func main() {}

This code looks “logical”: if there is no error, verr remains nil. But what we return is not *ValidationError, but error. And we get typed nil.

If you use it like this:

err := NewTask("ok")
if err != nil {
	// you will unexpectedly end up here
}

…then the application will start behaving as if “there is always an error”.

5. Diagnosing typed nil

Quick test: print (%T, %v)

When typed nil is suspected, there is a simple test: print (%T, %v).

The idea is this: if err != nil, but fmt.Printf("%T", err) shows *SomeType, while the value looks “like nil”, then you almost certainly wrapped a nil pointer in an interface.

A small helper that you can temporarily keep in the code:

package main

import "fmt"

func debugInterface(name string, x any) {
	fmt.Printf("%s: type=%T, value=%v\n", name, x, x)
}

func main() {
	var p *int = nil
	debugInterface("p", p) // p: type=*int, value=<nil>
}

Yes, any is also an interface too (just the “most general” one), but here we are using it only as a convenient diagnostic container, not trying to turn it into architecture.

Why printing sometimes shows <nil>, while comparison says “not nil”

This is the moment when many people think “the compiler is broken”. In fact, these are just different questions.

Printing a value often prints the dynamic value. If it is nil, you will see <nil> or something similar.

And the comparison iface == nil answers the question: “is there absolutely nothing in the interface?” That is, is there neither type nor value. With typed nil there is a type, so the answer is “no, the interface is not empty.”

The difficulty is that for a human, “emptiness” seems the same. For Go runtime, these are different states.

6. Practical rules

Two rules that really save a project

In interface topics, “abstract advice” often appears — advice that sounds nice but does not help in practice. Here the advice is as practical as possible — the kind you use tomorrow and the trap stops appearing.

The first rule sounds boring, but it works: if a function returns an interface (error, fmt.Stringer, your Store), then in the “nothing here” branch return the literal nil, not a variable that “is supposed to be nil”. This is especially important when the variable has a concrete type *T.

The second rule sounds like “turn on the flashlight”: when x behaves strangely != nil, print "%T". Type is half of the interface. Until you see it, it is as if you are trying to debug a box without opening the lid.

error is a normal interface

Today’s trap is especially nasty because error is not magic, but a normal interface:

type error interface {
	Error() string
}

And that is exactly why any type that has the method Error() string can be an error.
This is very powerful: you can make rich errors with context, fields, and logic, and the code will still work with them as a contract.

But “powerful” almost always means “you can shoot yourself in the foot”. Typed nil is one such shot: formally everything is correct, but the logic of expectations breaks.

7. Typical mistakes

Mistake #1: return (*T)(nil) as an interface and expect == nil.
This often appears when you store an error in a variable of a concrete pointer type (for example, *ValidationError) and return it as error. If the variable stayed nil, the interface can still become “not nil” because of the dynamic type. The cure is the habit of returning return nil in the success branch, not return somePtr.

Mistake #2: check the “wrong nil”.
Sometimes code checks if p == nil, and then uses iface, or the other way around. It is like the situation “I checked the door, but went in through the window”. If you work with an interface, check the interface; if you work with a pointer, check the pointer. And if you see strange behavior, print %T to understand what you are really checking.

Mistake #3: try to initialize an error “nicely” through a variable without thinking about the return type.
The construction “I will introduce var err *MyError, then return err” looks neat until the function returns an interface. In the interface world, “neat” must include the thought “am I wrapping typed nil?”

Mistake #4: assume that printing fmt.Println(err) is nil diagnostics.
Printing mostly shows the dynamic value, not the state of whether the interface is empty. So you can get <nil> on the screen and err != nil in logic. If you suspect typed nil, print fmt.Printf("%T", err) and compare err == nil.

Mistake #5: implicitly rely on the contract nil = success, but violate it in your own functions.
The Go code around you assumes that a nil error means success. If your function returns “not nil” in a successful case, you will get a cascade of strange effects: extra early returns, wrong messages, extra if branches. It is better to make return nil correct once than to heroically fix the consequences all over the code later.

1
과제
Go SELF, 레벨 24, 레슨 1
잠금
보이지 않는 직원
보이지 않는 직원
1
과제
Go SELF, 레벨 24, 레슨 1
잠금
유령 명함
유령 명함
1
과제
Go SELF, 레벨 24, 레슨 1
잠금
로그인 검증
로그인 검증
1
과제
Go SELF, 레벨 24, 레슨 1
잠금
Resource 제공
Resource 제공
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION