431

I'm learning Go but I feel it is a bit annoying that when compiling, I should not leave any variable or package unused.

This is really quite slowing me down. For example, I just wanted to declare a new package and plan to use it later or just uncomment some command to test. I always get the error and need to go comment all of those uses.

Is there any way to avoid this kind of check in Go?

A-letubby
  • 8,474
  • 8
  • 38
  • 48
  • 1
    possible duplicate of [Go: "variable declared and not used" compilation error](http://stackoverflow.com/questions/1718717/go-variable-declared-and-not-used-compilation-error) – bain Nov 19 '14 at 23:21
  • 18
    I still feel a compiler option would be useful for the "I want to comment something out to aid debugging" workflow. – RJFalconer Oct 23 '17 at 15:55
  • 118
    This feature is a great way to waste people's time lol, what is the point? When you commit/ship code, ok no unused vars is nice, but when developing it? Horrible. – Alexander Mills Dec 02 '18 at 03:48
  • 37
    It's 2020 and I can't believe they still haven't fixed this (not even with a compiler flag). I did a project in Go about 5 years ago and overall liked the language but it was unusable for me solely because of this. The way I code I am constantly commenting/uncommenting stuff, so this "feature" in Go makes things take double the time for me... I've been checking back every few months since then to see if a sense of reason has overtaken the Go team, and so far no luck... Sucks. It's a great language otherwise and I'd love to use it more, but currently it's just not useable for me. – Ruslan Apr 20 '20 at 18:30
  • As usual they thought this through. See the _ character usage in imports (below) and if you have a variable you are not ready to use at the moment (i.e. developing the code) a simple _ assignment will do. – Rick O'Shea Nov 02 '20 at 00:12
  • 11
    @RickO'Shea Assigning unused vars to a throwaway var `_` is still a very cumbersome work around which demonstrably breaks developer flow. Every single time you comment something out you then need to go and stub all the `declared but not used` errors. Any team could implement standards and style checks as a commit hook or part of a CI/Gate job. The lack of agency given to developers here is patronizing and furthermore forces us to write **_worse_** code in order to be able to pull things apart. `goimports` solves the issue for imports, a compiler flag should be acceptable for variables. – Simon Merrick Dec 03 '20 at 03:44
  • 4
    A use case for _unused variables_ is to have them show up in watches while debugging. I use this a lot and having to work around it with _ is really annoying. – Petruza Jul 25 '21 at 14:08
  • @AlexanderMills, well, it's the only way to ensure that errors are actually dealt with (if not explicitly ignored with `_`, of course). – Marvin H. Apr 13 '22 at 15:39
  • Check this video. https://www.youtube.com/shorts/HaHME-64Rdw – Tabriz Atayi Dec 14 '22 at 17:08
  • Late in the game, but I've had enought of unused variable error, so I've created a GoLand plugin to solve it similar to GoImports tool: https://plugins.jetbrains.com/plugin/20933-painlessgo Preview: https://youtu.be/sVVlDtQUXtU – David Horáček Feb 10 '23 at 11:37

12 Answers12

358

That error is here to force you to write better code, and be sure to use everything you declare or import. It makes it easier to read code written by other people (you are always sure that all declared variables will be used), and avoid some possible dead code.

But, if you really want to skip this error, you can use the blank identifier (_) :

package main

import (
    "fmt" // imported and not used: "fmt"
)

func main() {
    i := 1 // i declared and not used
}

becomes

package main

import (
    _ "fmt" // no more error
)

func main() {
    i := 1 // no more error
    _ = i
}

As said by kostix in the comments below, you can find the official position of the Go team in the FAQ:

The presence of an unused variable may indicate a bug, while unused imports just slow down compilation. Accumulate enough unused imports in your code tree and things can get very slow. For these reasons, Go allows neither.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Florent Bayle
  • 11,520
  • 4
  • 34
  • 47
  • 163
    Still, this is not so different from going commenting it out. And, I understand that this is for better code but would it be better if we can close a check why testing on our code and then open this check again after we want to finish the code and make it clean? – A-letubby Feb 13 '14 at 05:06
  • 4
    @A-letubby, the official position of Go devs is [in the FAQ](http://golang.org/doc/faq#unused_variables_and_imports); if you can't live with this, there's not much you can do. My personal opinion is that "quite slows down" is an overestimation: it takes me one run of `go build` to comment/blank whatever is not needed, and it's fast. And you know that the resulting program has quite big chances to be correct--contrary to scripting languages with faster modify-run cycle, where you'll get a runtime crash for a typo (read: unused variable). – kostix Feb 13 '14 at 05:55
  • 26
    @kostix Well.. it might not slow you down because you might be an expert but it is for me and the way I am coding. I am just wondering if there is better way. But anyway, thanks for the FAQ! By reading this, I can totally understand for what reasons golang is doing this way. – A-letubby Feb 13 '14 at 06:41
  • 26
    Is there a command-line argument to turn this off? Or is this an un-changeable feature? – Ethan Bierlein Jun 28 '15 at 22:58
  • 65
    FWIW, I've had bad times reading code of others, but definitely not due to unused symbols. OTOH, I lost an hour today investigating methods to deal with this *#%$ golang "feature". – Torsten Bronger Jan 17 '16 at 21:09
  • 55
    Sadly this answer is correct -- but that doesn't justify it. There's a world of difference between checking in code and simply executing it. When we check in code, we use linters to catch this kind of error. When we execute during rapid development, we don't have the same standards. It's unforgivable to confuse a compiler with a linter. Even the style police inside Google don't make that mistake. – Travis Wilson Apr 26 '17 at 22:23
  • 58
    thats a stupid decision from the Go's team. especially when trying to debug things. – Lucas Pottersky Aug 31 '18 at 18:22
  • 42
    Having the compiler treat this as an error is inexcusable. One can make the argument that this issue is the purview of linters and code style specs, but in the end the stupidity of making this a compile error comes up every time I'm doing some quick debugging and comment out a few lines of code. It's a sickening waste to have to go through the commented-out block and also comment out all of the declarations that were consumed there before I can compile. This turns a 2-second debugging habit into a slog that can burn 30x that long. The language spec has no business foisting this edict upon us. – Sniggerfardimungus Oct 29 '18 at 20:47
  • Yes go compilation is quicker and go code has less bug now. But my code-generator is rather slow and my hand-written code generator is much larger and more likely to have a bug. – recolic Mar 11 '19 at 11:04
  • 3
    I'm writing some code that is no more than tinkering/in-progress and I just want to run the debugger up to my code to verify, inspect, toy with some results. But because I'm not actually modifying said results, I can't compile. This is frustrating. The answer of using _ = seems to take care of my simple case, but it doesn't excuse the prevention of compilation of code I'm not checking in. The option of turning it off should be there. – user99999991 Mar 19 '19 at 17:11
  • 2
    If people want an option to suppress that error, means it would benefit them. It does not force you to write better code. Do folks cannot wrap their head around the difference between the final product and the development of a product? What a dogmatic decision for so called pragmatic language. – xged Apr 13 '19 at 07:24
  • 9
    I read this answer as, "Go is not a nuisance language. It's an intentional nuisance language". That albatross is not going to do anything for adoption. – micahhoover Apr 27 '19 at 14:24
  • 6
    I think this style police culture impedes development. For example, I am writing tests at the moment; I'm defining loads of arrays (that I'm not quite sure what I'm going to do with at the moment - but I know I'm going to use the data in these arrays for testing) and I want to just check that I'm writing with all the correct syntax and that I'm not using libraries incorrectly as I'm going along. When I compile the code to check for 'genuine' errors, the error output is cluttered with red herring (i.e. not using the arrays I've just declared). – Lost Crotchet Sep 25 '19 at 18:23
  • 5
    @LostCrotchet: Language designers should focus on ways of helping programmers write good code, not on trying to prevent them from writing bad code, or worse, preventing them from writing code that would meet a programmer's objectives in a way that the language designer doesn't like. – supercat Apr 07 '20 at 17:57
  • 5
    Where can I modify the Go compiler to disable this *expletive* annoying warning? – Petrus Theron Jul 28 '20 at 18:23
  • 8
    The position of the Go team completely misses the point. It's as though they've only read about software development in books and never done it themselves! I agree that this is a great feature, even to have on by default, but when debugging it's just a huge waste of time, and an absolutely unnecessary one, which could have been obviated with a simple policy of "don't ship code built with -suppress-warnings". – user1974458 Oct 24 '20 at 23:33
  • 5
    This is flatly a MISTAKE. Google thinks they know better than the last 70 years of computer scientists -- I'm not sure why Thompson didn't push back against this. I've been programming for 36 years now. I need warnings for these because I'm writing code very quickly and making many adjustments and experiments. This "feature" is cumbersome, forcing needless code modifications while doing rapid development. In other languages, my final builds error on warnings, but spits them out, sometimes suppresing some when doing development. This must be amended -- it is foolish. – Daniel Santos Dec 05 '20 at 13:03
  • 1
    @PetrusTheron `git clone git@github.com:golang/go.git`, examine `cmd/compile/internal/ssa/gen/rulegen.go` look for `unusedInspector`, modify and send me a patch! :) Better yet, add some command-line argument to disable it. – Daniel Santos Dec 05 '20 at 13:10
  • 2
    Go raises a compilation error when a variable is unused but does not complain when outputs of functions are ignored. It's inconsistent. Ignoring outputs is way worse as it may ignore errors, or just the function result. While an unused variable would takes 64 bits on heap/etc, which is totally neglictable and not related to code quality and neither performance – Galaad Feb 26 '21 at 13:30
  • This answer doesn’t answer the question. The question is about unused **variables**, not unused imports. – chmike Apr 10 '21 at 14:02
  • Testament to to how behind the times the language is – Mezz Jun 20 '22 at 02:02
  • GoLand plugin to workaround unused variables: https://plugins.jetbrains.com/plugin/20933-painlessgo – David Horáček Feb 09 '23 at 08:19
  • When it comes you are in emergency, you sometimes need to comment two or three lines of code putting a variable unused to ask later a colleague about them, and deliver to the customer what is corrected, without deleting any code. – Marc Le Bihan May 03 '23 at 12:48
  • Allowing to document parameters in function doc also helps developers to produce better code, but Go's team rejected it. So... – Marc Le Bihan May 03 '23 at 12:54
  • I agree. Sometimes when you're writing code, you want stuff to be unused temporarily for debugging. If you use _ the value is not available in the debugger. Temporarily writing blank code for debugging does not mean you are planning to check it in. – slipperypete Jun 24 '23 at 21:42
55

I ran into this while I was learning Go 2 years ago, so I declared my own function.

// UNUSED allows unused variables to be included in Go programs
func UNUSED(x ...interface{}) {}

And then you can use it like so:

UNUSED(x)
UNUSED(x, y)
UNUSED(x, y, z)

The great thing about it is, you can pass anything into UNUSED.

Is it better than the following?

_, _, _ = x, y, z

That's up to you.

chuacw
  • 1,685
  • 1
  • 23
  • 35
  • 2
    I find this method more useful than the blank identifier... As I'm developing in go, I like to run my code as early and as frequently as possible... It's more useful to me to make some variables "UNUSED" with my last line, than to comment out entire blocks that may not work as I expect. – erwin Oct 11 '20 at 00:56
  • 1
    This is a fantastic solution – GrandmasterB Mar 08 '21 at 05:51
  • Wonderfully concise, and easy to add that keyword to your linting system to ensure you "fix" it when it's actually necessary to do so. – PartyLich May 15 '22 at 17:45
  • Late in the game, but I've had enought of unused variable error, so I've created a GoLand plugin to solve it similar to GoImports tool: https://plugins.jetbrains.com/plugin/20933-painlessgo Preview: https://youtu.be/sVVlDtQUXtU – David Horáček Feb 10 '23 at 11:37
  • @DavidHoráček - nice! I wish you'd zoomed in on your text though - that video example was hard to watch. – mattmc3 May 24 '23 at 20:50
53

You can use a simple "null function" for this, for example:

func Use(vals ...interface{}) {
    for _, val := range vals {
        _ = val
    }
}

Which you can use like so:

package main

func main() {
    a := "declared and not used"
    b := "another declared and not used"
    c := 123

    Use(a, b, c)
}

There's also a package for this so you don't have to define the Use function every time:

import (
  "github.com/lunux2008/xulu"
)

func main() {
  // [..]

  xulu.Use(a, b, c)
}
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
lunux2008
  • 539
  • 4
  • 2
  • 6
    Is there a way to automatically use all declared vals instead? For development purposes this issue is really annoying =/ – GarouDan Mar 31 '21 at 13:40
  • 2
    It seems the loop is unnecessary, see this answer below https://stackoverflow.com/a/62951339/722796 – PJ Brunet Dec 09 '21 at 03:42
38

According to the FAQ:

Some have asked for a compiler option to turn those checks off or at least reduce them to warnings. Such an option has not been added, though, because compiler options should not affect the semantics of the language and because the Go compiler does not report warnings, only errors that prevent compilation.

There are two reasons for having no warnings. First, if it's worth complaining about, it's worth fixing in the code. (And if it's not worth fixing, it's not worth mentioning.) Second, having the compiler generate warnings encourages the implementation to warn about weak cases that can make compilation noisy, masking real errors that should be fixed.

I don't necessarily agree with this for various reasons not worth going into. It is what it is, and it's not likely to change in the near future.

For packages, there's the goimports tool which automatically adds missing packages and removes unused ones. For example:

# Install it
$ go get golang.org/x/tools/cmd/goimports

# -w to write the source file instead of stdout
$ goimports -w my_file.go

You should be able to run this from any half-way decent editor − for example for Vim:

:!goimports -w %

The goimports page lists some commands for other editors, and you typically set it to be run automatically when you save the buffer to disk.

Note that goimports will also run gofmt.


As was already mentioned, for variables the easiest way is to (temporarily) assign them to _ :

// No errors
tasty := "ice cream"
horrible := "marmite"

// Commented out for debugging
//eat(tasty, horrible)

_, _ = tasty, horrible
Community
  • 1
  • 1
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
  • 3
    "the Go compiler does not report warnings, only errors that prevent compilation." Useful information, but terrible approach from language authors – Michael Freidgeim Sep 02 '21 at 08:24
  • 1
    Yeah, hard to agree. I'm testing out Go myself and am coming across these "errors" not because the code needs to be fixed, but because the code is not finished. If I want to comment something out during debugging...I need to rework other parts due to unused variables. – mukunda Jan 10 '22 at 05:58
13

In case others have a hard time making sense of this, I think it might help to explain it in very straightforward terms. If you have a variable that you don't use, for example a function for which you've commented out the invocation (a common use-case):

myFn := func () { }
// myFn()

You can assign a useless/blank variable to the function so that it's no longer unused:

myFn := func () { }
_ = myFn
// myFn()
max pleaner
  • 26,189
  • 9
  • 66
  • 118
10

One angle not so far mentioned is tool sets used for editing the code.

Using Visual Studio Code along with the Extension from lukehoban called Go will do some auto-magic for you. The Go extension automatically runs gofmt, golint etc, and removes and adds import entries. So at least that part is now automatic.

I will admit its not 100% of the solution to the question, but however useful enough.

miltonb
  • 6,905
  • 8
  • 45
  • 55
9

As far as I can tell, these lines in the Go compiler look like the ones to comment out. You should be able to build your own toolchain that ignores these counterproductive warnings.

Petrus Theron
  • 27,855
  • 36
  • 153
  • 287
  • 1
    ah hah! Yeah, I had a nice patch for 1.15, but they've made massive changes to the sources since then. I had to re-write from scratch for 1.19. – Daniel Santos Jan 10 '23 at 04:15
7

I ran into this issue when I wanted to temporarily disable the sending of an email while working on another part of the code.

Commenting the use of the service triggered a lot of cascade errors, so instead of commenting I used a condition

if false {
    // Technically, svc still be used so no yelling
    _, err = svc.SendRawEmail(input) 
    Check(err)
}
maxime
  • 1,993
  • 3
  • 28
  • 57
0

My answer is to hack the f-ing sources. This patch works against 1.19.4 and then you build your sources with -gcflags all=-nounusederrors (you'll need help elsewhere in order to build Golang from sources):

tty/tty.go:98:6: hello declared but not used, but nobody cares

It doesn't suppress some unused labels and the grammar of the appended message is a bit sloppy, but nobody cares.

From 6eb19713fb5302ef2d5eb4af0c05e86c88d055c7 Mon Sep 17 00:00:00 2001
From: Daniel Santos <daniel.santos@pobox.com>
Date: Mon, 9 Jan 2023 21:56:03 -0600
Subject: Add -nounusedwarnings

---
 src/cmd/compile/internal/base/flag.go       |  1 +
 src/cmd/compile/internal/types2/errors.go   | 10 ++++++++++
 src/cmd/compile/internal/types2/labels.go   |  2 +-
 src/cmd/compile/internal/types2/resolver.go |  8 ++++----
 src/cmd/compile/internal/types2/stmt.go     |  4 ++--
 src/cmd/go/alldocs.go                       |  2 ++
 src/cmd/go/internal/work/build.go           |  2 ++
 src/go/types/gotype.go                      |  3 +++
 8 files changed, 25 insertions(+), 7 deletions(-)

diff --git a/src/cmd/compile/internal/base/flag.go b/src/cmd/compile/internal/base/flag.go
index a363b83984..f295746f64 100644
--- a/src/cmd/compile/internal/base/flag.go
+++ b/src/cmd/compile/internal/base/flag.go
@@ -111,6 +111,7 @@ type CmdFlags struct {
    MemProfileRate     int          "help:\"set runtime.MemProfileRate to `rate`\""
    MutexProfile       string       "help:\"write mutex profile to `file`\""
    NoLocalImports     bool         "help:\"reject local (relative) imports\""
+   NoUnusedErrors     bool         "help:\"no errors for unused imports and variables\""
    Pack               bool         "help:\"write to file.a instead of file.o\""
    Race               bool         "help:\"enable race detector\""
    Shared             *bool        "help:\"generate code that can be linked into a shared library\"" // &Ctxt.Flag_shared, set below
diff --git a/src/cmd/compile/internal/types2/errors.go b/src/cmd/compile/internal/types2/errors.go
index 2a3e88a2fe..0405fa26de 100644
--- a/src/cmd/compile/internal/types2/errors.go
+++ b/src/cmd/compile/internal/types2/errors.go
@@ -8,6 +8,7 @@ package types2
 
 import (
    "bytes"
+   "cmd/compile/internal/base"
    "cmd/compile/internal/syntax"
    "fmt"
    "runtime"
@@ -275,6 +276,15 @@ func (check *Checker) softErrorf(at poser, format string, args ...interface{}) {
    check.err(at, check.sprintf(format, args...), true)
 }
 
+func (check *Checker) unusedf(at poser, format string, args ...interface{}) {
+   if base.Flag.NoUnusedErrors {
+       pos := posFor(at)
+       fmt.Printf("%s: %s, but nobody cares\n", pos, check.sprintf(format, args...))
+   } else {
+       check.softErrorf(at, format, args)
+   }
+}
+
 func (check *Checker) versionErrorf(at poser, goVersion string, format string, args ...interface{}) {
    msg := check.sprintf(format, args...)
    if check.conf.CompilerErrorMessages {
diff --git a/src/cmd/compile/internal/types2/labels.go b/src/cmd/compile/internal/types2/labels.go
index 6f02e2fc96..d3ae602549 100644
--- a/src/cmd/compile/internal/types2/labels.go
+++ b/src/cmd/compile/internal/types2/labels.go
@@ -35,7 +35,7 @@ func (check *Checker) labels(body *syntax.BlockStmt) {
    for name, obj := range all.elems {
        obj = resolve(name, obj)
        if lbl := obj.(*Label); !lbl.used {
-           check.softErrorf(lbl.pos, "label %s declared but not used", lbl.name)
+           check.unusedf(lbl.pos, "label %s declared but not used", lbl.name)
        }
    }
 }
diff --git a/src/cmd/compile/internal/types2/resolver.go b/src/cmd/compile/internal/types2/resolver.go
index 5d498b6b2b..935435b03f 100644
--- a/src/cmd/compile/internal/types2/resolver.go
+++ b/src/cmd/compile/internal/types2/resolver.go
@@ -731,15 +731,15 @@ func (check *Checker) errorUnusedPkg(obj *PkgName) {
    }
    if obj.name == "" || obj.name == "." || obj.name == elem {
        if check.conf.CompilerErrorMessages {
-           check.softErrorf(obj, "imported and not used: %q", path)
+           check.unusedf(obj, "imported and not used: %q", path)
        } else {
-           check.softErrorf(obj, "%q imported but not used", path)
+           check.unusedf(obj, "%q imported but not used", path)
        }
    } else {
        if check.conf.CompilerErrorMessages {
-           check.softErrorf(obj, "imported and not used: %q as %s", path, obj.name)
+           check.unusedf(obj, "imported and not used: %q as %s", path, obj.name)
        } else {
-           check.softErrorf(obj, "%q imported but not used as %s", path, obj.name)
+           check.unusedf(obj, "%q imported but not used as %s", path, obj.name)
        }
    }
 }
diff --git a/src/cmd/compile/internal/types2/stmt.go b/src/cmd/compile/internal/types2/stmt.go
index 74d4164ba9..c4255e4413 100644
--- a/src/cmd/compile/internal/types2/stmt.go
+++ b/src/cmd/compile/internal/types2/stmt.go
@@ -66,7 +66,7 @@ func (check *Checker) usage(scope *Scope) {
        return unused[i].pos.Cmp(unused[j].pos) < 0
    })
    for _, v := range unused {
-       check.softErrorf(v.pos, "%s declared but not used", v.name)
+       check.unusedf(v.pos, "%s declared but not used", v.name)
    }
 
    for _, scope := range scope.children {
@@ -804,7 +804,7 @@ func (check *Checker) typeSwitchStmt(inner stmtContext, s *syntax.SwitchStmt, gu
            v.used = true // avoid usage error when checking entire function
        }
        if !used {
-           check.softErrorf(lhs, "%s declared but not used", lhs.Value)
+           check.unusedf(lhs, "%s declared but not used", lhs.Value)
        }
    }
 }
diff --git a/src/cmd/go/alldocs.go b/src/cmd/go/alldocs.go
index a3c1fecb91..1f4c5c7b5c 100644
--- a/src/cmd/go/alldocs.go
+++ b/src/cmd/go/alldocs.go
@@ -179,6 +179,8 @@
 //     directory, but it is not accessed. When -modfile is specified, an
 //     alternate go.sum file is also used: its path is derived from the
 //     -modfile flag by trimming the ".mod" extension and appending ".sum".
+// -nounusederrors
+//     do not error on unused functions, imports, variables, etc.
 // -overlay file
 //     read a JSON config file that provides an overlay for build operations.
 //     The file is a JSON struct with a single field, named 'Replace', that
diff --git a/src/cmd/go/internal/work/build.go b/src/cmd/go/internal/work/build.go
index 5f11cdabaf..b37f1c8a01 100644
--- a/src/cmd/go/internal/work/build.go
+++ b/src/cmd/go/internal/work/build.go
@@ -135,6 +135,8 @@ and test commands:
        directory, but it is not accessed. When -modfile is specified, an
        alternate go.sum file is also used: its path is derived from the
        -modfile flag by trimming the ".mod" extension and appending ".sum".
+   -nounusederrors
+       do not error on unused functions, imports, variables, etc.
    -overlay file
        read a JSON config file that provides an overlay for build operations.
        The file is a JSON struct with a single field, named 'Replace', that
diff --git a/src/go/types/gotype.go b/src/go/types/gotype.go
index e8ff9658da..5a60b83346 100644
--- a/src/go/types/gotype.go
+++ b/src/go/types/gotype.go
@@ -47,6 +47,8 @@ The flags are:
        verbose mode
    -c
        compiler used for installed packages (gc, gccgo, or source); default: source
+   -nounusederrors
+       treat "unused" errors as warnings
 
 Flags controlling additional output:
 
@@ -104,6 +106,7 @@ var (
    allErrors  = flag.Bool("e", false, "report all errors, not just the first 10")
    verbose    = flag.Bool("v", false, "verbose mode")
    compiler   = flag.String("c", "source", "compiler used for installed packages (gc, gccgo, or source)")
+   nounusederr= flag.Bool("nounusederrors", false, "treat unused objects as warnings")
 
    // additional output control
    printAST      = flag.Bool("ast", false, "print AST")
-- 
2.38.2


Disclaimer: this isn't a comprehensive patch -- it only affects running go build or the compile tool. Should still have errors when using ast (tree parser), tracing and a few others tools because I didn't mess with internal/types, only cmd/compile/internal/types2 -- the Golang sources are a bit messy like that. I'm hoping they can refactor at some point and get rid of these redundancies.

Daniel Santos
  • 3,098
  • 26
  • 25
0

I just made a new Golang compiler, which will simply ignore all variable unused warning and import unused warning by default.

https://github.com/yingshaoxo/go/releases/tag/v1.21

It works for both go run and go build

yingshao xo
  • 244
  • 7
  • 11
0

You can define as package level, still gives warning but can compile without error.

package main
import "fmt"

var i, x int = 1, 2

func main() {
  fmt.Println("Hello")
}

Go playground

Intellij screenshot

0

You can also do x = x, as a beginner go programmer I have to admit this is the most annoying language I've seen:)

baz
  • 1,317
  • 15
  • 10