CodeGym /Các khóa học /Go SELF /Interface value: (type, value)

Interface value: (type, value)

Go SELF
Mức độ, Bài học
Có sẵn

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 it. That is a natural desire: the brain already has enough to deal with. But it is exactly because of this “box” that the most annoying bugs appear — when you checked err == nil, the logic went down the “no error” branch, but the program still behaves as if an error existed. Or the opposite: err != nil, yet you print err and see <nil>, and start suspecting that Go is trolling you.

The problem is not Go and not your luck. The problem is that the 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 at 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, “some 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 handy “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 keep mixing 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 between a “nil pointer” and a “nil interface”.

Let us put it 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 character. That is exactly typed nil: inside the interface there is nil, but “with a passport” (with a concrete type).

2. Code demonstrations

Nil interface and %T

Now we will make 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, no value.

Typed nil: the interface is “not nil”, although inside there is nil

Now let us make a 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 there is a dynamic type *Person. 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 that printing is safe. This is not an obligatory language rule, but a conscious defense: if a method with 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 we have an unwritten agreement: nil error means success. And a big part of Go code is built on that: we constantly compare an error with 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 is wrapped in error
}

func main() {
	err := validateTitle("hello")
	fmt.Println(err == nil)        // false (and this 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 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

So that this does not remain abstract, let us imagine that we are continuing a mini app 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 close to the boundary (where the entity is created). Now it is important for us to make sure that the contract “nil = success” does not break.

A 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 stays 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 there is suspicion of typed nil, there is a simple test: print (%T, %v).

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

A mini 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 (just the “most general” one), but we are using it here only as a convenient diagnostic container, without trying to turn it into architecture.

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

This is the moment where many people think “the compiler is broken”. In fact, it is 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 nothing at all 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 person, “emptiness” seems the same. For the 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 apply 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 “should 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 != nil behaves strangely, print "%T". Type is half of the interface. Until you see it, it is as if you are debugging a box without opening the lid.

error is a regular interface

Today’s trap is especially nasty because error is not magic, but a regular 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 with a contract.

But “powerful” almost always means “you can shoot yourself in the foot”. Typed nil is one of those shots: 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 fix 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 vice versa. This is like the situation “I checked the door, but entered through the window.” If you are working with an interface — check the interface, if you are working with a pointer — check the pointer. And if you see weirdness — print %T to understand what you are really checking.

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

Mistake #4: assume that printing fmt.Println(err) is diagnostics for nil.
Printing mostly shows the dynamic value, not the state of whether the interface is empty. That is why you can get <nil> on the screen and err != nil in the 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 the success case, you will get a cascade of strange effects: extra early returns, wrong messages, extra if branches. It is better to make return nil correctly once than to heroically fix the consequences throughout the code later.

1
Nhiệm vụ
Go SELF, mức độ, bài học
Đã khóa
Nhân viên vô hình
Nhân viên vô hình
1
Nhiệm vụ
Go SELF, mức độ, bài học
Đã khóa
Danh thiếp bóng ma
Danh thiếp bóng ma
1
Nhiệm vụ
Go SELF, mức độ, bài học
Đã khóa
Kiểm tra tên đăng nhập
Kiểm tra tên đăng nhập
1
Nhiệm vụ
Go SELF, mức độ, bài học
Đã khóa
Cấp phát tài nguyên
Cấp phát tài nguyên
Bình luận
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION