How to stop GoLand from auto removal of unused imports? - go

I am working with JetBrains GoLand and wondering if it's possible to somehow disable the auto removal of unused imports. I have searched the JetBrains forums earlier and there is no such information specifically for Goland.

This feature is used so that you do not receive compilation errors for unused imports from Go. You can deactivate the feature via:
Settings (Preferences) > Go > Imports > Optimize imports on the fly
However my recommendation is to leave this as is and instead let the IDE manage the imports for you.
For example, you can start typing template.New inside the main function and the IDE will ask which "template" package to import as there are two packages in the standard library "text/template" and "html/template". When only one package is available, that will be imported automatically. When you will remove the last reference to the "template" package, the IDE will remove the import automatically, thus allowing you to run the code without any compilation issues.

Another solution is to name your import as "_". For example: import _ "your/package". Doing this will prevent auto removal.

The behavior was slightly changed in the 2021.2 version of GoLand and higher (GO-11362).
Previous behavior (2021.1.3 and lower):
Current one (2021.2 and higher):
So, it was slightly updated and there is no reason to disable Optimize imports on the fly, but as dlsniper said you can start typing your code and import packages later. It is a bit convenient way.

If disabling it doesn't work in File | Settings | Go | Imports | Unchecked Optimized Imports On the fly You can disable it in the on action Save menu
optimize imports enabled in File | Settings | Tools | Actions on Save | Uncheck Optimized Imports
REF: https://youtrack.jetbrains.com/issue/GO-6881/Goland-deletes-code-import-statements-are-deleted-automatically-before-I-even-get-an-opportunity-to-use-them#focus=Comments-27-6124465.0-0

Preferences:
Languages & Frameworks
Go
Imports
Optimize imports on the fly

Related

Golang: Can't use syscall.EpollCreate

I am trying to port a program from C to Go, so using a lot of stuff from the syscall package is required.
I am trying to use https://pkg.go.dev/syscall#EpollCreate, but VSCode refuses to autocomplete it for me or recognize that it is a defined function. FWIW, I get autocomplete for many other things in the syscall package.
My project is using Go 1.14. I am unsure how to tell what version of Go things were introduced in, so I am wondering if that is my problem.
I tried creating a dummy project that uses Go 1.17 and still no luck.
I am writing the code on a Mac, but it will eventually be compiled for ARM Linux, if that matters.
So is this a Go problem or a VSCode problem? Both? Neither?
Sample dummy project:
go.mod:
module epoll-noodle
go 1.14
main.go:
package main
import (
"syscall"
)
func main() {
syscall.EpollCreate(4)
}
It turns out that if you are developing for a platform that differs from your own, some things may be unsupported (like EpollCreate in this case, as #JimB said). The Go extension does let you change your env vars though, so you can work around this in VSCode. In your extensions settings, put something like:
{
"go.toolsEnvVars": {"GOOS" : "linux"}
}
and your project will be built for that OS.
The settings file can be found in the .vscode folder in the root of your project. If there isn't one, you can go to the Go extension in VSCode and fiddle with some settings (for the workspace, not the user) and it will create one for you. Then edit as necessary.
See also: https://github.com/microsoft/vscode-go/issues/632

How to annotate symbols that they are shared among other projects?

Suppose I have a Go project which act as shared library in another Go project. How do I markup Go symbols (consts, structs, vars) that they are used outside this project?
I guess the underlying problem is that I have a hard time knowing which code uses said symbols.
Please note: This is not about semantic versioning, of which I am very well aware and which I use. I know Semver can help to identify breaking changes.
Instead, this is about finding out if I actually break one of my own projects (compared to: This symbol should be unexported or used outside the package). I am thinking of some sort of annotation which don't exist in Go.
As an aside, IntelliJ doesn't know either and marks those symbols as "Unnecessarily exported". Maybe an IntelliJ-centric solution could suffice.
To illustrate my problem:
package sharedlib
import "time"
// MyFavoriteTimeFormat is a blablabla...
const MyFavoriteTimeFormat = Time.RFC3339
package dependingproject
import "github.com/thething/sharedlib"
import "time"
func convertToString(timestamp time.Time) string {
return timestamp.Format(sharedlib.MyFavoriteTimeFormat)
}
When I happily rename MyFavoriteTimeFormate and release it, the code will break in the depending project when it updates the dependency.
Don't export anything until some other package needs it. If another package needs something, then do export, and then you'll know that if something is exported, it is because it is used outside of the package. And do not do breaking changes on exported identifiers. If you really must, then increment major version. Using go modules, that won't break existing other packages, they will continue to use the old version.
If your module is broken down into multiple packages (because it is "big"), and you wish to export something solely for the other packages of your module, then use the internal package concept, so it will still be "unexported" (unimportable) to other modules. For details, see Can I develop a go package in multiple source directories?

GoLand (JetBrains) shows error message "Unresolved Reference". But Code compiles and runs

I am writing a project using the Go language with GoLand IDE by Jetbrains.
While writing the code, GoLand shows me an error message such as "unresolved reference" when the reference do exist and that the program compiles and runs correctly.
Here is a similar (but simpler) example of some code that I have found here on stackoverflow (Go - append to slice in struct) to reproduce this issue.
The same error message appears even though I have implemented the methods just a few lines above.
package main
import (
"fmt"
)
type MyBoxItem struct {
Name string
}
type MyBox struct {
Items []MyBoxItem
}
func (box *MyBox) AddItem(item MyBoxItem) {
box.Items = append(box.Items, item)
}
func main() {
item1 := MyBoxItem{Name: "Test Item 1"}
item2 := MyBoxItem{Name: "Test Item 2"}
box := MyBox{}
box.AddItem(item1)
box.AddItem(item2)
// checking the output
fmt.Println(len(box.Items))
fmt.Println(box.Items)
}
box.AddItem(item1) and box.AddItem(item2) are marked red as an error. If I move my cursor above it, it says unresolved reference "AddItem". Yet the code compiles and runs. And as this was the solution to an other stackoverflow question, I do not think that the code is wrong. Furthermore I cannot find any mistakes in it.
[EDIT: I load the code from a remote server and edit it locally on my private pc. After finishing my changes, I upload it to the remote server (using GoLands tools like "Browse remote host") and build and compile it there. After trying it out locally with the very same code, the error message sometimes is there and sometimes not. I am totally confused]
I experienced a similar issue, but it was a lot more prevalent. Even things like fmt.Printf() were showing as unresolved. Was able to resolve the issue by going to File -> Invalidate Caches / Restart.
I found best way to fix this issue.
close your project and IDE
go to your project directory
remove ./.idea
try to open it again
woops woops, fixed
Edit : better way try to use this one in Goland Menu
file -> repair IDE
it will be refresh index module
Today I faced that problem and I fixed it by enabling go module integration. For that
Settings -> Other Settings -> Go Modules then enable go modules integration.
This will work if you using go modules in your project.
I'm using go module and it's solved by:
Deselect Preferences->Go->GOPATH->Use GOPATH that's defined in system environment
File->Invalidate caches / Restart
I'm a bit late to the answer lol but incase anyone is still running into this, all I did was delete the .idea file and reloaded the project on GoLand (by clicking File -> Open -> file location). Did the trick for me.
I just removed the project from Goland and re-create it from existing files. It was weird but it worked.
I cannot reproduce the issue in GoLand 2020.2. I suggest upgrading to it.
If that doesn't fix the issue then you can take the following steps to investigate the issue:
Is your project using Go modules or the traditional GOPATH?
If it's using GOPATH, have you enabled indexing of GOPATH under Settings/Preferences | Go | GOPATH?
If it's using Go modules, check to see that the support is enabled under Settings/Preferences | Go | Go Modules and then use Alt+Enter | Sync packages of‍‍ <project>
For me the issue was the version of Golang, I had been using go1.19 which threw unreferenced errors with .Close methods, switching back to an older version go16.15 helped me resolve this issue.
I had a similar issue for gin.WrapH function utils.go. Tried the Override File Type option for utils.go in local module path which changed the file as a Go file but had a little cross sign where a tooltip marked that the file is excluded from compilation. The error Unresolved reference only went away when I selected the file, navigated to File -> File Properties -> Associate with File Type -> Register new file type association, and chose Go files
No option from other comments helped me. I had to switch GO SDK version in Setting -> Go -> GOROOT. Goland automatically downloaded 1.16 beta 1 version and it worked.
In Goland preferences, if you're using the Global GOPATH, check the option "Index entire GOPATH" and hit apply.
I had the same issue, I did try invalidates cache, but that did not work.
But the thing worked is just add a below line in your idea.properties file. And then restart IDE.
# custom GoLand properties (expand/override 'bin/idea.properties')
idea.max.intellisense.filesize=100000
This is because, Goland does not index huge packages. But you can force it to do that.
For Mac users, i solved this by setting Custom Tags to 'unix'.
In Preferences > Go > Build Tags & Vendoring. In the Custom Tags, input unix.
I'm using GoLand 2022.1.2
I had the same problem and it got fix weirdly.So I installed and opened project in vscode in order to continue coding.It started installing a extension called gopls. After installation completed I returned to GoLand to close project, but I waited for indexing to complete.Suddenly references were green !
Goland version 2020.1: I opened a folder with subfolders of golang projects and goland didn't recognize dependencies. I solved this problem setting Project GOPATH
ctrl + alt + s
Go > GOPATH
Click on plus button + In Project GOPATH
Add your golang's project folder, example: ~/projects/my-golang-projects
I faced the same issue when I do bazel run //:gazelle, I fixed this issue by doing bazel sync (Bazel -> Sync -> Sync Project with BUILD Files). But you should have the below settings.
(This fix is for Goland IDE, Mac. Of course we should add GOPATH in .bash_profile or .zshrc)
I had the same issue with aws go sdk, changing the Custom Properties (Help -> Edit Custom Properties) helped me.
here is the reference to the JetBrains thread https://youtrack.jetbrains.com/issue/GO-5029
idea.max.intellisense.filesize=10000
idea.max.content.load.filesize=20000
Restart the IDE to let the changes take effect.
I had been using go1.19 which threw unreferenced errors with .Close methods. I download the GoLand 2022.2.4 package and install, issue has been solved.
In my case, I fixed it by running go mod tidy in the console.
In my case go mod was 1.18 and IDE indexed my project with 1.19.
At Preferences -> GOROOT I selected Go 1.18 and problem solved.
Today face the same problem using GoLand 2021.3 MacOS.
Fixed it with go to File Menu -> Repaire IDE...
Then it will automatic fixing issues
I solved it by reinstall Go to D:\go, then reset Go sdk.

Import ReactiveCocoa, or PromiseKit, or BrightFutures as sources?

I have an OSX project (xcode plugin) and I want to use the ReactiveCocoa paradigms in it (PromiseKit andBrightFutures` are the other implementations of the same paradigms so I need to import at least one from these 3 frameworks/libraries).
The problem is it seems impossible to import them as compiled frameworks into my project because it is plugin. In my project I used dispatch_async and dispatch_after functions only but their nested blocks look awful.
The only solution I found is import one from these frameworks as sources but I don't know how to detach their code. So could anybody help with this trouble? Or maybe are there any other similar libraries which are already represented as source files only?
Short Answer:
Use a dependency manager like Cocoapods or Carthage.
Longer Answer: You can do it manually, but even if you don't want to use any of those, you can look at the .podspec file and see how it's supposed to be used. For example BrightFutures.podspec says:
s.source_files = 'BrightFutures/*.swift'
s.dependency 'Result', '0.6.0-beta.6'
That means that you need to import all the .swift files inside the BrightFutures folder, and that it won't work unless you also import the files from another project called Result.
But please, just let the tools do that for you. You'll be happier. :)

Does Xcode have resolve imports functionality?

In Eclipse, I rarely have to manually import a file due to its ability to automatically resolve imports using a keyboard shortcut. Is this available in Xcode?
Does that mean automatically add the correct #import lines?
Nope.
On the other hand, Cocoa code tends to just pull in the world. As far as system headers, it's pretty normal to only need <Cocoa/Cocoa.h>, which is already in the template Xcode use for a new file. You can use a prefix header in your project to cover your own headers.

Resources