• Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Ineffective Assignment to Field when trying to update a Struct in Go

I'm getting the linting error

when I try to use a struct method LevelUp to update the struct's value Player.Level :

p.Level also remains 0 after calling p.LevelUp() . What is the proper way to call a method that updates the value of a field of the struct this method is attached to?

icza's user avatar

Each parameter including the receiver is copied upon entering the function / method. When you return, the changes made to the copy are lost. That's why you get a warning: you modify a field which you never use: you don't use in in the method after the assignment, and you can't possibly use it anywhere else, because after returning from the method, the effect of the assignment is lost.

If you need to retain the changes, you must use a pointer receiver ( p *Player ) and modify the pointed object ( p.Level++ will do just that).

This will output (try it on the Go Playground ):

See related:

My object is not updated even if I use the pointer to a type to update it

How to modify the value of a simple type through pointer receiver method in Go?

Why can't I append to a slice that's the property of a struct in golang?

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged go methods struct or ask your own question .

  • The Overflow Blog
  • Ryan Dahl explains why Deno had to evolve with version 2.0
  • From PHP to JavaScript to Kubernetes: how one backend engineer evolved over time
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • Op Amp Feedback Resistors
  • Why would aliens want to invade Earth?
  • What does 北渐 mean?
  • One IO to control two LEDs. When one is lit, the other is not
  • Is there racial discrimination at Tbilisi airport?
  • Fast circular buffer
  • Are there any virtues in virtue ethics that cannot be plausibly grounded in more fundamental utilitarian principles?
  • In the US, can I buy iPhone and Android phones and claim them as expense?
  • Thai word not breaking properly between lines, in LuaLaTeX
  • Short story in which the protagonist shrinks to the size of his model train set and is run over by one of his trains
  • How to raise a vector to powers contained in a vector, change the list into a product, and do this for all the lines of a matrix, efficiently?
  • How to justify a ban on single-deity religions?
  • The hat-check problem
  • Calculate the sum of numbers in a rectangle
  • Print tree of uninstalled dependencies and their filesizes for apt packages
  • TeXbook Exercise 21.10 Answer
  • Can figere come with a dative?
  • What does the Fizeau experiment now do?
  • Sticker on caption phone says that using the captions can be illegal. Why?
  • Explaining Arithmetic Progression
  • Does my AC vent air from the room to outside?
  • What's the Matter?
  • Assumptions in a ideal circuit which consists of ideal wires(zero resistance)
  • Is there anything that stops the majority shareholder(s) from destroying company value?

ineffectual assignment to data (ineffassign)

Two linters I'll always add to new Go projects: errcheck and ineffassign

Jul 17, 2020

The reason for that is that they are the best bang for your buck by far. They are easy to appease, I have yet to see them produce false positives, they very frequently catch outright buggy code and retrofitting them is a pain.

ineffassign

This is the sort of thing that ineffassign prevents:

This is perfectly valid code, and will write garbage sometimes, without any indication whatsoever. Yes, Go does refuse to compile code like this

because data is not used, but declaring a variable and then immediately overwriting its value is perfectly legal and almost never what you want. At best the variable was never needed, in which case a _ is a good way to signal it, or it was meant to be used and ineffassign found a bug.

I’ve seen this pattern frequently enough in tests, where part of the test code accidentally doesn’t check intermediate errors or return values, leading to parts of the test silently breaking over time.

To its credit, gopls does check for this now .

In a similar vein, errcheck enforces checking error return values. In Go, errors are values, and unlike other 1 languages 2 , nothing enforces they are checked.

This is valid:

And so are all these:

The only difference is that the first example carries no indication where this was intentional or not. errcheck enforces that error values are at least assigned to _ , therefore being explicit that a decision was made to ignore the error 3 .

One case where this matters is when writing new code. It’s easy enough to forget about checking all error returns of all functions called. Again, tests passing by accident is a very frequent occasion, and so is production code.

Another also interesting case is functions changing signatures. When adding an error return to a function that previously returned nothing or updating a dependency that does so, you probably want to verify all the call sites, at the very least making the executive choice to explicitly ignore the errors.

Retrofitting using golangci-lint

golangci-lint has positioned itself as the tool everyone uses on CI, and I’d say with good reason. It supports many linters, has improved massively over the past couple of years and has facilities for wiring up into existing codebases by only checking code that changes 4 , allowing for incremental cleanup.

For example:

No one has to fix the unchecked error, until they touch the call in bar() . This works well, until you realise there are transformations where this heuristic falls flat. This is still true according to the latest golangci-lint, 1.28.3.

Here is an example of this in action:

Since the call to foo() is not touched, golangci-lint considers the unchecked error pre-existing and does not report it! The check is completely elided on changes that simply go from zero returns to a single error return. This simply makes the check not as useful as it could be, allowing regressions to merge over time.

The other problem with retrofitting is that the cleanup can be boring and take a long time. Clearing hundreds for errors in bulk is mind-numbing. Merely shifting around existing code might require fixing existing issues, unrelated to the change at hand.

Why go through that, when simply adding these linters from the start does the trick and saves you from bugs?

Addendum - 18th July

I got a bit curious about k8s’ code, and ran ineffassign against it. There is one case where ineffassign could be considered noisy, and that is using foo := true instead of var foo bool :

The code in question:

This nudges towards var exist bool or bool := false . Clearly there is no bug here, the result is the same either way, so it boils down to the style used when declaring variables.

good  ↩

Rust  ↩

Not necessarily a good decision, you can always find yourself staring at git blame wondering why.  ↩

according to git and revgrep, using the new- settings in the config . Nowadays it works, a long time ago I found out the hard way it didn’t   ↩

go初学踩坑:ineffectual assignment to 变量 (ineffassign)错误

ineffectual assignment to data (ineffassign)

最近在写一些go的代码,在写到一个一行代码的时候,突然出现了这么一个错误:

其中content是我的一个变量,我的代码如下:

这里使用了 :=赋值,我却出现了这个报错,一直没能去掉,后来发现,这应该是go强制的一个要求,必须我要对这些变量做处理使用,这个奇怪的报错才能去掉,如下:

主要是我go的代码写得太少,才会出现这种google上人家都赖得问的问题。。在这里记录下来也是为了给自己一个提醒,希望下次不要再犯。

ineffectual assignment to data (ineffassign)

请填写红包祝福语或标题

ineffectual assignment to data (ineffassign)

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

ineffectual assignment to data (ineffassign)

| | | | | |
| | | | on:
Since you generally test the happy path more diligently, subtleties like these tend to show up later than desirable (compile time would be the most desirable, of course).

The := semantics is partly to blame here, as well as Go's lack of laziness around unused values. Go is curiously strict about unused , which never hurt anyone, as opposed to unused , which absolutely can hurt. For example:

This is much worse! And the compiler doesn't complain. Fortunately there's a linter called ineffassign that tracks ineffective assignments, and it's part of gometalinter and golangci-lint. But not "go vet". And there's no linter that can detect the first example that I gave.

Shadowing is a pet peeve of mine. Go is one of the strictest, most opinionated languages in mainstream use, but it's amazingly lax and unopinionated in certain areas. "go vet" can check for shadowing, but doesn't do so by default, and of course it doesn't test the subtype of shadowing that := causes. Shadowing is usually a bad idea, but Go encourages it through its := assignment semantics.


|
| |

api: add golangci-lint with gosec and fix the related warnings

  • Review changes
  • Check out branch
  • Overview 23
  • Pipelines 1

This MR adds golangci-lint to follow best practice. Besides the default linters, gosec is enabled.

Original warnigns are below,

Merge request reports

fix ineffectual assignment to err (ineffassign)

ineffectual assignment to data (ineffassign)

54 unxz_test.go Unescape Escape View File

aFile.Close()
, err := ioutil.ReadAll(aFile)
err != nil {
.Fatal(err)
, err := os.Open(path.Join(currentDir(), "./test/out/a.txt"))
err != nil {
aOutFile.Close()
, err := ioutil.ReadAll(aOutFile)
err != nil {
.Fatal(err)
string(aFileContent) != string(aOutFileContent) {
.Fatal("Unxz file content error.")
bFile.Close()
, err := ioutil.ReadAll(bFile)
err != nil {
.Fatal(err)
, err := os.Open(path.Join(currentDir(), "./test/out/b.txt"))
err != nil {
bOutFile.Close()
, err := ioutil.ReadAll(bOutFile)
err != nil {
.Fatal(err)
string(bFileContent) != string(bOutFileContent) {
.Log(string(bFileContent))
cOutFile.Close()
, err := ioutil.ReadAll(cOutFile)
err != nil {
.Fatal(err)
, err := os.Open(path.Join(currentDir(), "./test/out/dir/c.txt"))
err != nil {
cOutLinkFile.Close()
, err := ioutil.ReadAll(cOutLinkFile)
err != nil {
.Fatal(err)
string(cOutFileContent) != string(cOutLinkFileContent) {
.Fatal("Unxz file content error or link file content error.")
cOutFileNew.Close()
, err := ioutil.ReadAll(cOutFileNew)
err != nil {
.Fatal(err)
.Log("New c.txt content:", string(cOutFileContentNew))
, err := os.Open(path.Join(currentDir(), "./test/out/dir/c.txt"))
cOutLinkFileNew.Close()
, err := ioutil.ReadAll(cOutLinkFileNew)
err != nil {
.Fatal(err)
string(cOutFileContentNew) != string(cOutLinkFileContentNew) {
.Fatal("Unxz file link error.")
testSymlink(t *testing.T) {
, err := filepath.EvalSymlinks(path.Join(currentDir(), "./test/out/d.txt"))
err != nil {
.Fatal(err)
targetURL != path.Join(currentDir(), "./test/out/dir/d.txt") {
.Fatal("Unxz file Symlink error.")
dOutSymlinkFile.Close()
, err := ioutil.ReadAll(dOutSymlinkFile)
err != nil {
.Fatal(err)
, err := os.Open(path.Join(currentDir(), "./test/out/dir/d.txt"))
err != nil {
dOutFile.Close()
, err := ioutil.ReadAll(dOutFile)
err != nil {
.Fatal(err)
string(dOutSymlinkFileContent) != string(dOutFileContent) {
.Fatal("The content of symlink file is not equal to that of target file")
eOutFile.Close()
, err := ioutil.ReadAll(eOutFile)
err != nil {
.Fatal(err)
, err := os.Open(path.Join(currentDir(), "./test/out/dir/e.txt"))
err != nil {
eOutLinkFile.Close()
, err := ioutil.ReadAll(eOutLinkFile)
err != nil {
.Fatal(err)
string(eOutFileContent) != string(eOutLinkFileContent) {
.Fatal("Unxz file content error or link file content error.")
eOutFileNew.Close()
, err := ioutil.ReadAll(eOutFileNew)
err != nil {
.Fatal(err)
.Log("New dir/dir/e.txt content:", string(eOutFileContentNew))
, err := os.Open(path.Join(currentDir(), "./test/out/dir/e.txt"))
eOutLinkFileNew.Close()
, err := ioutil.ReadAll(eOutLinkFileNew)
err != nil {
.Fatal(err)
string(eOutFileContentNew) != string(eOutLinkFileContentNew) {
.Fatal("Unxz file link error.")
testSymlinkInDir(t *testing.T) {
, err := filepath.EvalSymlinks(path.Join(currentDir(), "./test/out/dir/dir/f.txt"))
err != nil {
.Fatal(err)
.Log("F outSymlinkFile link:", inDirTargetURL)
inDirTargetURL != path.Join(currentDir(), "./test/out/dir/f.txt") {
fOutSymlinkFile.Close()
, err := ioutil.ReadAll(fOutSymlinkFile)
err != nil {
.Fatal(err)
, err := os.Open(path.Join(currentDir(), "./test/out/dir/f.txt"))
err != nil {
fOutFile.Close()
, err := ioutil.ReadAll(fOutFile)
err != nil {
.Fatal(err)
string(fOutSymlinkFileContent) != string(fOutFileContent) {
.Fatal("The content of symlink file is not equal to that of target file")

The note is not visible to the blocked user.

ineffassign

This package is not in the latest version of its module.

Detect ineffectual assignments in Go code.

This tool misses some cases because does not consider any type information in its analysis. (For example, assignments to struct fields are never marked as ineffectual.) It should, however, never give any false positives.

Documentation ¶

There is no documentation for this package.

Source Files ¶

  • ineffassign.go

Keyboard shortcuts

: This menu
: Search site
or : Jump to
or : Canonical URL

IMAGES

  1. Uncaught ineffective assignment · Issue #15 · gordonklaus/ineffassign

    ineffectual assignment to data (ineffassign)

  2. Golang Lint Error ineffectual assignment to hubGroupIDs (ineffassign)

    ineffectual assignment to data (ineffassign)

  3. Data Analysis INDIVIDUAL ASSIGNMENT

    ineffectual assignment to data (ineffassign)

  4. SOLUTION: Assignment 1 descriptive statistics data analysis plan doc

    ineffectual assignment to data (ineffassign)

  5. Inefficiency of information sharing kit713

    ineffectual assignment to data (ineffassign)

  6. Data Structure Assignment

    ineffectual assignment to data (ineffassign)

COMMENTS

  1. Why is lint giving a warning ineffectual assignment to (ineffassign)

    Jun 23, 2021 at 5:25. 2. @Ishmeet, note that the linter wasn't forcing you to use a var declaration; instead it hinted at that you might have a bug in your code—because the first assignment could be way more involved like assigning the return value of some function call which would return a value inintialized in a complicated way, and ...

  2. GitHub

    ineffassign. Detect ineffectual assignments in Go code. An assignment is ineffectual if the variable assigned is not thereafter used. This tool misses some cases because it does not consider any type information in its analysis. For example, assignments to struct fields are never marked as ineffectual. It should, however, never give any false ...

  3. "Ineffectual assignment" false positive when var used in deferred

    ineffassign version: last version available go version: go version go1.18.3 Running the linter when interacting with a var after passing it to a deferred function call marks it as ineffectual assignment package main import "errors" func ...

  4. methods

    That's why you get a warning: you modify a field which you never use: you don't use in in the method after the assignment, and you can't possibly use it anywhere else, because after returning from the method, the effect of the assignment is lost. If you need to retain the changes, you must use a pointer receiver ( p *Player) and modify the ...

  5. github.com/gordonklaus/ineffassign

    An assignment is ineffectual if the variable assigned is not thereafter used. This tool misses some cases because it does not consider any type information in its analysis. For example, assignments to struct fields are never marked as ineffectual. ... ineffassign returns 1 if any problems were found in the checked files. It returns 3 if there ...

  6. Two linters I'll always add to new Go projects: errcheck and ineffassign

    because data is not used, but declaring a variable and then immediately overwriting its value is perfectly legal and almost never what you want. At best the variable was never needed, in which case a _ is a good way to signal it, or it was meant to be used and ineffassign found a bug.

  7. How to Detect Unused Variables After Reassignment?

    There are static code checkers which detect such, for example golangci-lint and staticcheck $ golangci-lint run x.go:15:8: ineffectual assignment to err (ineffassign) num2, err := strconv.Atoi("a") $ $ staticcheck ./... x.go:15:2: this value of err is never used (SA4006)

  8. Incorrect ineffectual assignment in switch #57

    I found a false ineffectual assignment in a case similar to this: package main import ( "fmt" ) func main() { var a int switch n := -1; { case n == -1: n += 1 fallthrough case n == 0: a = 10 } fmt.Println(a) } It says that n += 1 is inef...

  9. go初学踩坑:ineffectual assignment to 变量 (ineffassign)错误-CSDN博客

    go初学踩坑:ineffectual assignment to 变量 (ineffassign)错误 28060 photoshop中 怎么改变一张png图片的颜色 26143 Android Studio报错:Unsupported method: AndroidProject.getPluginGeneration()的一种解决方法 26134

  10. Linters

    ineffassign Detects when assignments to existing variables are not used. ... Finds wasted assignment statements. style: v1.38.0: ... -G203 # Use of unescaped data in HTML templates-G204 # Audit use of command execution-G301 # Poor file permissions used when creating a directory

  11. ineffectual assignment to err (ineffassign) (#7249)

    Checklist I'm using the latest version of the extension (Run glab...

  12. It's also suprisingly easy to mess up error returning. I've

    Fortunately there's a linter called ineffassign that tracks ineffective assignments, and it's part of gometalinter and golangci-lint. But not "go vet". And there's no linter that can detect the first example that I gave. Shadowing is a pet peeve of mine. Go is one of the strictest, most opinionated languages in mainstream use, but it's ...

  13. Uncaught ineffective assignment · Issue #15 · gordonklaus/ineffassign

    package main import "fmt" func main() { var i int i = 3 i = 5 fmt.Println(i) } $ ineffassign main.go does not produce any results. It should catch that the i = 3 assignment was ineffective (its value was never used). I created the issue ...

  14. api: add golangci-lint with gosec and fix the related warnings

    $ golangci-lint run ./api/ --disable-all-E deadcode -E gosimple -E gosec -E govet -E ineffassign -E staticcheck -E structcheck -E typecheck -E unused -E varcheck ... G203: this method will not auto-escape HTML. Verify data is well formed. (gosec ... = http.Get (url) oauth_github_callback.go:12:8: ineffectual assignment to ` err ` (ineffassign ...

  15. ineffassign command

    ineffassign. Detect ineffectual assignments in Go code. This tool misses some cases because does not consider any type information in its analysis. (For example, assignments to struct fields are never marked as ineffectual.) It should, however, never give any false positives.

  16. ineffassign command

    ineffassign. Detect ineffectual assignments in Go code. This tool misses some cases because it does not consider any type information in its analysis. (For example, assignments to struct fields are never marked as ineffectual.) ... ineffassign returns 1 if any problems were found in the checked files. It returns 3 if there were any invalid ...

  17. Ineffassign False Positive When Using Defer #627

    It rather relies on checks that it gets from other linters (such as govet, staticcheck, ineffassign, etc). As a result your "new check" suggestion would be more actionable if made to another GitHub project. The nature of the suggested check makes it, in my opinion, a prime candidate for go-critic.

  18. fix ineffectual assignment to err (ineffassign) · ae2ceefcf9

    fix ineffectual assignment to err (ineffassign) ... yi-ge 5 years ago. parent 368962abf3. commit ae2ceefcf9. 1 changed files with 54 additions and 0 deletions. 54. unxz_test.go. Unescape.

  19. Enable ineffassign in the linter and fix issues #2215

    area/testing Issue related to testing the operator-sdk and subcomponents good first issue Denotes an issue ready for a new contributor, according to the "help wanted" guidelines. help wanted Denotes an issue that needs help from a contributor. Must meet "help wanted" guidelines. kind/flake Categorizes issue or PR as related to a flaky test.

  20. github.com/golangci/ineffassign

    ineffassign. Detect ineffectual assignments in Go code. This tool misses some cases because does not consider any type information in its analysis. (For example, assignments to struct fields are never marked as ineffectual.) It should, however, never give any false positives.

  21. ineffectual assignment to `err` · Issue #338 · dgrijalva/jwt-go

    http_example_test.go:57:12: ineffectual assignment to `err` (ineffassign) listener, err := net.ListenTCP("tcp", &net.TCPAddr{}) The text was updated successfully, but these errors were encountered: All reactions. Copy link Owner. dgrijalva commented Jun 20, 2019. Let's just track ...

  22. arthurfiorette/proposal-safe-assignment-operator

    While this proposal is still in its early stages, we are aware of several limitations and areas that need further development: Nomenclature for Symbol.result Methods: We need to establish a term for objects and functions that implement Symbol.result methods. Possible terms include Resultable or Errorable, but this needs to be defined.. Usage of this: The behavior of this within the context of ...