CodeGym /행동 /Go SELF /go vet — error classes: printf, shadow, and friends

go vet — error classes: printf, shadow, and friends

Go SELF
레벨 30, 레슨 2
사용 가능

1. 코드 품질 프로세스에서 go vet의 위치

Go compiler is strict: if types do not match or syntax is broken, it simply will not let you build the program. But there is another class of problems: code that is formally correct, compiles, and sometimes even “seems to work”, but inside it hides an expectation error. go vet is exactly about such cases: it looks at the code and says, “I think you are doing something strange right now — check whether that is really what you intended.”

You can think of go vet as an attentive pair on code review who never gets tired, is not distracted by coffee, and does not write the comment “well, you get it.” It does not replace tests and does not prove program correctness, but it catches many typical “almost bugs” before execution — and that saves you hours of life and a couple of nerve cells.

By the way, historically vet was a separate tool, and then it was “packed” under the go command, just like many other Go ecosystem utilities.

Where it sits in the verification chain

When you start writing code that is “a bit more serious than one file with 20 lines”, a normal engineering need appears: agree on what counts as minimum acceptable quality. We already cover formatting and imports with tools (for this day — gofmt and goimports), and go vet is naturally placed as the next layer: it checks whether there are constructions that often mean an error.

A handy mental model is this: formatting makes code readable, vet catches suspicious spots, and tests confirm behavior in scenarios.

flowchart LR
    A["Code written"] --> B["Formatting (gofmt/goimports)"]
    B --> C["Static analysis (go vet)"]
    C --> D["Tests (go test)"]
    D --> E["You can feel okay about it (within reason)"]

It is important to understand the boundary: go vet is static analysis, meaning it does not run your program, but analyzes the source code. It does not know “how it will really behave in prod”, but it can find patterns that often end in bugs.

How to run go vet and read its messages

At this stage of the course, it is enough to know how to run go vet on a project and read the result without panic. Usually the command checks a package or all packages at once. In the terminal this is often done with something like go vet ./..., and in an IDE there is usually a menu item that does the same thing (just with a button, which, to be honest, is nice).

vet messages usually look like “in file X at line Y there is a suspicious construction Z”. This is not a sentence, but a signal: stop, understand the meaning, and either fix it or consciously leave it as is (rare, but it happens). The most common beginner mistake is to see a message and think, “well, later.” No — it is like a “check engine” light: the car may still drive, but better not pretend it does not exist.

What “error class” means in go vet

Inside go vet there is a set of separate checks — it is convenient to think of them as “analyzers” (analyzer). Each analyzer looks for its own type of problem: one looks at format strings Printf, another at strange struct tags, a third at variable shadowing, and so on.

Why is it important to think in terms of “classes”? Because you start recognizing patterns. If you understand the printf class, you begin to suspect a problem automatically even before vet: “okay, %d and a string… this will definitely end badly.” And when you know the structtag class, you stop treating tags like “magic spells” and start seeing ordinary strings with a strict format in them.

Below we will look at the most useful classes for your current level: printf, string(int) conversion, shadow, structtag, “unkeyed struct literals from another package” (composites), and unusedresult.

3. The printf class: format does not match arguments

fmt.Printf is a very powerful thing, but it has a cost: it accepts arguments as ...any. That means the compiler cannot strictly check that your %d really received a number, and your %s really received a string. And that is where a favorite bug genre appears: “everything compiles, but the output is strange… or maybe there is a panic… or the data goes sideways.”

Type mismatch: %d and a string

Look at the example — it compiles, but is obviously suspicious:

package main

import "fmt"

func main() {
	age := "10"
	fmt.Printf("age=%d\n", age) // wanted a number, got a string
}

The fix depends on the meaning. If age is a string, print %s. If it is “a number that came as a string”, then parse it with strconv.Atoi and print %d.

Mismatch in argument count

Another typical failure is forgetting an argument or adding an extra one:

package main

import "fmt"

func main() {
	name := "Bob"
	fmt.Printf("hello %s %d\n", name) // %d did not get an argument
}

go vet likes to catch such things, because this is almost always an error.

A mini example in our learning app

Let us imagine that we have a simple task model:

package main

import "fmt"

type Task struct {
	ID    int
	Title string
}

func main() {
	t := Task{ID: 7, Title: "Buy milk"}
	fmt.Printf("task id=%s title=%s\n", t.ID, t.Title) // printing ID as a string
}

Correct version:

fmt.Printf("task id=%d title=%s\n", t.ID, t.Title) // task id=7 title=Buy milk

Pay attention: we do not “force” data to fit the format. We choose the format for the data. It is like shoes: sure, you can try to wear sneakers on your head, but it is still better to do it the other way around.

4. The string(int) class: why is string(10) not "10"?

Many beginners honestly think: “well, if it is int, then you can convert it to string.” In Go you can write string(n), and the code will compile, but the meaning will not be “a number as text” — it will be “a Unicode character with code n”. For example, string(65) gives "A".

This construct exists historically, but it confuses people so regularly that diagnostic checks were even added in vet for it, because it is a classic trap.

Trap demonstration

package main

import "fmt"

func main() {
	n := 65
	fmt.Println(string(n)) // A
}

If you wanted "65", you need strconv.Itoa(n):

package main

import (
	"fmt"
	"strconv"
)

func main() {
	n := 65
	fmt.Println(strconv.Itoa(n)) // 65
}

How this shows up in a task app

A very real situation: you are printing a task ID by building a string:

package main

import "fmt"

func main() {
	id := 10
	fmt.Println("task " + string(id)) // suddenly: "task \n"
}

10 as a character code is a newline, so you get a line break, not “10”. And if you look at this and think, “yeah, some kind of magic”, then congratulations: you have just met the most ordinary strict semantics of the language.

5. The shadow class: variable shadowing and the danger of :=

Shadowing is when you create a new variable with the same name in an inner block, and it “hides” the outer one. Formally everything is correct, but it is easy to end up in a situation like “I thought I updated the variable, but in fact I created a new one and updated it.”

Yes, we already discussed shadowing earlier, but here the practical aspect matters: go vet (and some other tools) can highlight such spots, especially when they look like a mistake.

It is also useful to remember separately: shadowing often happens because of :=. This is exactly why in Go people recommend treating := as a great tool, but not as “put it everywhere where you are too lazy to think.”

By the way, a similar problem is described in the context of the typical mistake “accidentally shadowed a slice variable and then kept using the old one.”

Mini example: “the error got lost”

package main

import (
	"errors"
	"fmt"
)

func main() {
	var err error

	if true {
		err := errors.New("boom") // created a NEW err
		_ = err
	}

	if err == nil {
		fmt.Println("all good") // all good (but we were supposedly doing boom?)
	}
}

The fix is to replace := with = where you want to update an existing variable:

if true {
	err = errors.New("boom") // updated the outer err
}

Shadowing in argument parsing code

Imagine that we have a function that parses a task ID from a string:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	idStr := "42"
	id := 0

	if n, err := strconv.Atoi(idStr); err == nil {
		id := n // shadowed id, outer one stayed 0
		_ = id
	}

	fmt.Println(id) // 0
}

This is a logical error: you wanted to write n into the outer id, but wrote := and created a new id inside the if. The fix:

if n, err := strconv.Atoi(idStr); err == nil {
	id = n
}

6. The structtag class: “it is just a string… why did it break?”

Struct tags look like magic: backticks, and inside them a mini-language. But technically it is just a string literal that external libraries read according to certain rules. If you make a format mistake, the compiler often stays silent (tags do not affect execution directly), but the library may start behaving differently from what you expected.

That is why go vet checks suspicious tags: for example, when the format looks wrong. This is especially relevant after you have already seen tags like json:"name,omitempty" and understand that the comma and quotes are not there for decoration.

Example: “almost right, but no”

package main

type Task struct {
	ID int `json: "id"` // space and colon are in the wrong place: looks suspicious
}

func main() {}

Correct:

package main

type Task struct {
	ID int `json:"id"`
}

func main() {}

Example closer to our app

Suppose we have a task model in the model package:

package model

type Task struct {
	ID    int    `json:"id"`
	Title string `json:"title"`
	Done  bool   `json:"done"`
}

Yes, we are not serializing tasks to JSON yet (that will be a separate big topic), but tags can already live in the model as a “future contract”: the main thing is that they are correct, otherwise in the future you will get a funny bug “why is the field not parsing”, and the culprit will be a space in a tag from the past.

7. The composites class: positional struct literals from another package

In Go, you can create a struct positionally: Task{1, "Title", false}. It works, but it has one downside: if you add a field or change the order, the old code will either stop compiling or, worse, compile but change meaning.

go vet really likes to complain about unkeyed struct literals from another package. Why? Because this is considered a fragile API contract: you depend on the field order of someone else’s type, and that is not something pleasant to sign up for.

Example using our model and app packages

Suppose in model:

package model

type Task struct {
	ID    int
	Title string
	Done  bool
}

And in app you create a task like this:

package app

import "example.com/tasker/model"

func NewDemo() model.Task {
	return model.Task{1, "Read Go book", false} // positional
}

It is better to write with field names:

return model.Task{
	ID:    1,
	Title: "Read Go book",
	Done:  false,
}

It takes a couple more lines, but it is more readable and more resilient to structure changes.

8. The unusedresult class: “I called a function… why did nothing happen?”

There are functions that return a result, and if you ignore it, that is usually an error. For example, fmt.Sprintf does not print; it returns a string. Beginners sometimes expect, “well, it is fmt, so it must have printed.” No, it did not print. A string was simply born and died alone.

go vet can highlight ignoring the result of some functions, because this is the classic “it seems you mixed up Sprintf and Printf”.

Example: Sprintf with the result unused

package main

import "fmt"

func main() {
	fmt.Sprintf("hello %s", "Bob") // string created and thrown away
	fmt.Println("done")            // done
}

The correct variant depends on the goal:

If you wanted to print:

fmt.Printf("hello %s\n", "Bob") // hello Bob

If you wanted to get a string:

s := fmt.Sprintf("hello %s", "Bob")
fmt.Println(s) // hello Bob

A similar mistake in a task app

package main

import "fmt"

func main() {
	id := 3
	fmt.Sprintf("selected task id=%d", id) // forgot to use it
}

If the goal is to show the user, use Printf/Println.

9. A small “correct” fragment for the app

Let us assemble a small piece of code that feels “friendly” to vet: the format matches, there is no string(int) trap, no strange tags, no positional literals from another package, and no shadowing.

package main

import (
	"fmt"
	"strconv"
)

type Task struct {
	ID    int    `json:"id"`
	Title string `json:"title"`
	Done  bool   `json:"done"`
}

func main() {
	idStr := "7"

	id, err := strconv.Atoi(idStr)
	if err != nil {
		fmt.Printf("bad id=%q\n", idStr) // bad id="..."
		return
	}

	t := Task{ID: id, Title: "Buy milk", Done: false}
	fmt.Printf("task id=%d title=%s done=%v\n", t.ID, t.Title, t.Done)
	// task id=7 title=Buy milk done=false
}

The important thing here is not that this is “perfect code”. The important thing is that it is predictable: each expression does exactly what is written, and quality tools will stay silent — and silence from tools, oddly enough, is sometimes the nicest sound in development.

10. Typical mistakes when working with go vet

Mistake #1: treating go vet like “another compiler” and being afraid of every warning.
vet does not promise 100% accuracy: it says “looks like a bug.” Your job is to understand why it looks like a bug and make a decision. In educational projects, the right answer is almost always to fix it, because warnings usually point to a genuinely wrong expectation.

Mistake #2: fixing a warning mechanically without understanding the meaning.
For example, seeing “printf: wrong type” and just changing %d to %v. Yes, the message disappears, but you may have lost an important idea: are you printing a string as a number or a number as a string? That is a symptom of the wrong data model. It is better to stop for a second and ask yourself: “what type should this really be?”

Mistake #3: not noticing string(int) and trying to “fix” output with a hack.
When you see "task \n" instead of "task 10", do not write “if the character is strange — print differently.” You need to understand: string(int) is a character by code, not a number. And after that, calmly switch to strconv.Itoa. The reason analyzers highlight this at all is that this mistake is incredibly typical for beginners.

Mistake #4: ignoring variable shadowing because “it compiles anyway.”
Shadowing is one of the most insidious bugs: the outer variable stays with the old value, while you are sure you updated it. This is especially painful in code with errors (err) and with value changes after if. If you see a suspicious := inside a block, that is a great reason to check whether you actually wanted =.

Mistake #5: keeping positional struct literals “because it is shorter.”
Yes, it is shorter. But the price is fragility. As soon as the structure changes — and structures change almost always — you either break the build or get a silent bug. And that is where vet works like a vaccine: a little discipline now is better than an investigation later into “why did Done suddenly become Title”.

1
과제
Go SELF, 레벨 30, 레슨 2
잠금
출력 사양
출력 사양
1
과제
Go SELF, 레벨 30, 레슨 2
잠금
작업 번호
작업 번호
1
과제
Go SELF, 레벨 30, 레슨 2
잠금
선택된 식별자
선택된 식별자
1
과제
Go SELF, 레벨 30, 레슨 2
잠금
go vet 경고 없이
go vet 경고 없이
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION