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.

enter image description here

[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]


Solution 1:

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.

Solution 2:

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

Solution 3:

Today I faced that problem I fixed it to enable go module integration. For that Settings -> Go -> Go modules then enable go modules integration. This will work if you using go modules in your project.

Solution 4:

I just removed the project from Goland and re-create it from existing files. It was weird but it worked.