CodeGym /행동 /Go SELF /error as an interface — nil/not nil

error as an interface — nil/not nil

Go SELF
레벨 16, 레슨 0
사용 가능

1. Errors in Go: values and the error interface

If you come to Go after languages that have exceptions, the first cultural shock usually looks like this: "Why do I need to check for an error after almost every second call?" That feeling is normal: your brain is used to the idea that an error is something supernatural, while in Go it is as down-to-earth as possible — literally a variable that can be assigned, returned from functions, and printed.

One of the key slogans in the Go world sounds like this: errors are values. That is exactly why Go encourages explicit checks of err instead of some "escape" up the stack, where somebody somewhere will try to "catch" an exception. This style makes control flow more predictable: you can see where the program may "trip", and you can see exactly what will happen at that point.

In practice, this means one simple thing: if a function can fail (for example, it parses a number, reads input, opens a file), it usually returns a second result of type error. And then you decide what to do: terminate the program, ask the user to enter the value again, choose a default value, skip the record, and continue. But the decision is made by the code, not by an "exception system".

The error type: what it really is

Now comes an important point: error is a type, and not just any type — an interface type. In the Go standard library it is defined roughly like this:

type error interface {
    Error() string
}

If you have not studied interfaces "systematically" yet, that is still fine. For today's lecture, it is enough to understand an interface very pragmatically: an interface is a contract that says "this value has these methods". Here the contract is minimal: if a value has the Error() method returning string, then that value can be used as error.

And this is where the good news starts: it explains several strange things that usually scare beginners.

  • First, error is not a string. It can produce a string via Error(), but by itself it is not a string.
  • Second, errors can have different "internal" (concrete) types: strconv.Atoi returns one concrete error type, fmt.Scan may return another, and so on. But from the outside we keep them in a variable of type error, because the common contract is enough for us: "you can get text".
  • Third, that is exactly why fmt can print errors nicely: it knows that an error has the Error() method and can call it.

To see the idea "interface = method contract" in a simple way, here is a tiny demo:

package main

import "fmt"

type myError struct{}

func (myError) Error() string { // implement the error contract
	return "something went wrong"
}

func main() {
	var err error = myError{}
	fmt.Println(err) // something went wrong
}

There is no magic here: myError has the Error() method, so it can be stored in a variable of type error.

nil as a sign of success: the zero value for error

Now for the most practical Go rule: nil in error means success. And not-nil means an error occurred. This is not a "special operator" but a convention that supports the whole Go style.

It is important that the zero value for a variable of type error is exactly nil. So if you declare var err error, then "by default" you have "no error".

package main

import "fmt"

func main() {
	var err error // zero value for error is nil
	fmt.Println(err == nil) // true
	fmt.Println(err)        // <nil>
}

Pay attention to the second print: fmt.Println(err) outputs <nil>. This is not the string "nil", but a special output format for a nil value.

Now let's connect this with what we saw earlier in strconv.Atoi. If parsing succeeds, err will be nil. If it fails, err will be not nil, and inside there will be a concrete error object.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	n, err := strconv.Atoi("42")
	fmt.Println(n)          // 42
	fmt.Println(err == nil) // true
}

And now — a provocation:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	n, err := strconv.Atoi("4x")
	fmt.Println(n)   // 0
	fmt.Println(err) // strconv.Atoi: parsing "4x": invalid syntax
}

Here we can see two facts at once.

  • First: on error, n became 0 — this is the zero value for int.
  • Second: the error contains text that explains what happened.

And this leads us to discipline: if err != nil, the result (n) cannot be considered valid, even if it looks "plausible". Today it may be 0, tomorrow (in other functions) it may be an empty string, a nil slice, and so on.

How fmt prints errors

A very common beginner question: "Why does fmt.Println(err) print normal text if err is not a string?" The correct answer is: fmt prints errors by calling the Error() method on the error value.

So when you write fmt.Println(err), conceptually it is similar to "print err.Error()", except that fmt also knows how to handle the case where err == nil gracefully.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	_, err := strconv.Atoi("x")

	fmt.Printf("as %%v: %v\n", err) // as %v: strconv.Atoi: parsing "x": invalid syntax
	fmt.Println("as Println:", err) // as Println: strconv.Atoi: parsing "x": invalid syntax
}

Both variants use the same idea: fmt sees a value of type error and knows how to convert it into text.

Another useful diagnostic trick is printing the type with %T. This is especially useful when you want to understand which exact error is inside the error interface:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	_, err := strconv.Atoi("x")
	fmt.Printf("type: %T\n", err) // type: *strconv.NumError
}

The output *strconv.NumError is a hint: "inside error there is a concrete error structure from the strconv package". It is useful to remember that error is a wrapper (an interface), and inside it can be anything as long as there is an Error() method.

err.Error() and why we do not analyze error text

When you see err.Error(), that is not "magic" but an ordinary method call via dot: "call the Error method on the object err". Strictly by the error contract, this method returns string.

Sometimes you really need the string itself, for example to concatenate it with your own message or to show only the text to the user. In that case err.Error() is appropriate.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	_, err := strconv.Atoi("x")
	if err != nil {
		fmt.Println("message:", err.Error()) // message: strconv.Atoi: parsing "x": invalid syntax
	}
}

But there is an important discipline here: we do not make decisions by analyzing the error text. In other words, this is a bad idea:

// an example of what NOT to do (do not copy)
if err != nil && strings.Contains(err.Error(), "invalid syntax") {
    ...
}

Why is it bad? Because the error text is a message for a human (log/output), not a stable API for a program. Today it is one thing, tomorrow another.

The correct rule for today is simple: we make the "success/error" decision by err == nil or err != nil, not by strings.

strconv.Atoi as a factory of real error values

The word "interface" sometimes sounds too abstract, so it is useful to turn it into our most familiar source of errors — strconv.Atoi. Let's look at two runs: "success" and "error", and in both cases print both the type and the value of err.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	_, err1 := strconv.Atoi("10")
	fmt.Printf("err1: %v (%T)\n", err1, err1) // err1: <nil> (<nil>)

	_, err2 := strconv.Atoi("1O") // letter O instead of zero
	fmt.Printf("err2: %v (%T)\n", err2, err2) // err2: ... (*strconv.NumError)
}

Notice that for err1 the type is printed as <nil>. This is normal: the interface variable error does not contain a concrete value, and therefore %T shows <nil>.

For err2 a concrete type appears: *strconv.NumError. That is the "concrete error" hidden behind the interface.

And this is why Go is so convenient to work with: you do not need to know everywhere that it is *strconv.NumError. It is enough to know: if err != nil, the operation failed, and the error can be printed or returned further.

2. Mini app "Expense tracking"

Now let's build a small educational example that will evolve further in the lesson about errors. The idea is as everyday as possible: we have a list of expenses, each expense is a category and an amount. We want to calculate the total and the sum by category. And we also want the program not to pretend everything is fine if the user enters "one hundred euros" instead of 100.

Let's make the input format simple: first a number n (how many records), then n pairs of category amount. The amount comes as a string, and we parse it with strconv.Atoi to get a classic error (not a "silent conversion to zero").

Let's start by writing a small function that reads one token. This will let us see in one place that even fmt.Scan can return an error.

package main

import "fmt"

func readToken() (string, error) {
	var s string
	_, err := fmt.Scan(&s)
	return s, err
}

Now let's make a function that reads the amount: it reads a string token and tries to convert it into an int.

package main

import (
	"strconv"
)

func readAmount() (int, error) {
	token, err := readToken()
	if err != nil {
		return 0, err
	}
	return strconv.Atoi(token)
}

The return style is important here: if an error occurs, we return 0 (the zero value for int) and the error itself. We are not improving the error text yet — today what matters is understanding that it is just a value and it is either nil or not.

Now let's assemble main, which reads n, then n records, and accumulates sums by category in map[string]int.

package main

import (
	"fmt"
)

func main() {
	n, err := readAmount()
	if err != nil {
		fmt.Println("failed to read n:", err)
		return
	}

	totals := make(map[string]int)

	for i := 0; i < n; i++ {
		cat, err := readToken()
		if err != nil {
			fmt.Println("failed to read category:", err)
			return
		}

		amount, err := readAmount()
		if err != nil {
			fmt.Println("failed to read amount:", err)
			return
		}

		totals[cat] = totals[cat] + amount
	}

	fmt.Println("totals:", totals)
}

This version is intentionally simple: at the first error, we print a message and exit. From the point of view of today's topic, this is ideal because it shows the main contract: as long as err == nil, we continue; as soon as err != nil, we choose the "error" branch.

To see that the program behaves predictably, imagine this input:

3
food 120
taxi 300
food x

On the third record, strconv.Atoi("x") will return a not-nil error, amount will become 0, and we will not add a "zero expense" as if everything were fine — we will stop and show the user the problem.

Notice another important thing about map: if there is no sum for the category yet, totals[cat] gives 0 (the zero value for int). Therefore the expression totals[cat] = totals[cat] + amount works both for the first record and for subsequent ones.

A small flowchart for the control flow looks like this (and it is a good template for the future):

flowchart TD
    A[Read a token/number] --> B{err == nil?}
    B -- yes --> C[Use the value]
    C --> A
    B -- no --> D[Show the error]
    D --> E[Stop]

3. Typical mistakes when taking first steps with error

Mistake #1: treating error as a string and checking "empty / not empty".
Sometimes you want to do something like if err != "", because "well, an error is text". But error is a separate type, not a string. A check is correct only through err == nil or err != nil. If you need text, you get it through err.Error(), but that is already a subsequent step, not a way to determine whether an error happened.

Mistake #2: printing the error and continuing calculations with an invalid result.
Situation: n, err := strconv.Atoi(...), then you print the error but still use n. The problem is that on error n will almost always be the zero value (for int that is 0), and you will silently get the wrong total. If you decided that the error is critical, then after the message there must be an explicit control-flow transition (for example, return from main).

Mistake #3: confusing "success" and "error" in the condition.
It is easy to write if err == nil { ... error handling ... }. Keep the rule in mind: err != nil is the error branch.

Mistake #4: not understanding that fmt.Println(err) is not just "printing a variable".
The text appears because fmt calls the Error() method on the error. It is useful to remember this so that you do not expect error to be a string "by itself".

Mistake #5: trying to make decisions based on err.Error() text.
The temptation is strong: the text is understandable. But it is not meant for branching logic. Get used to the discipline: we decide whether there is an error or not through nil/not-nil. The text is for the user/log, not for the algorithm.

1
과제
Go SELF, 레벨 16, 레슨 0
잠금
오류 센서
오류 센서
1
과제
Go SELF, 레벨 16, 레슨 0
잠금
자체 경보
자체 경보
1
과제
Go SELF, 레벨 16, 레슨 0
잠금
숫자 통과
숫자 통과
1
과제
Go SELF, 레벨 16, 레슨 0
잠금
지출 정산기
지출 정산기
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION