- 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?
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?
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)错误
最近在写一些go的代码,在写到一个一行代码的时候,突然出现了这么一个错误:
其中content是我的一个变量,我的代码如下:
这里使用了 :=赋值,我却出现了这个报错,一直没能去掉,后来发现,这应该是go强制的一个要求,必须我要对这些变量做处理使用,这个奇怪的报错才能去掉,如下:
主要是我go的代码写得太少,才会出现这种google上人家都赖得问的问题。。在这里记录下来也是为了给自己一个提醒,希望下次不要再犯。
请填写红包祝福语或标题
1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。
IMAGES
COMMENTS
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 ...
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 ...
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 ...
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 ...
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 ...
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.
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)
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...
go初学踩坑:ineffectual assignment to 变量 (ineffassign)错误 28060 photoshop中 怎么改变一张png图片的颜色 26143 Android Studio报错:Unsupported method: AndroidProject.getPluginGeneration()的一种解决方法 26134
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
Checklist I'm using the latest version of the extension (Run glab...
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 ...
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 ...
$ 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 ...
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.
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 ...
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.
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.
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.
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.
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 ...
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 ...