I have a vscode workspace with a couple of go modules. I have a top-level go.work
file.
I have installed the go plugin and installed all its dependencies. I have initialized separate modules in the workspace and have ran go use
to add all the modules to my go.work
file.
Unfortunately I didn't realize packages were generally named like "github.com/my-org/my-package/utils" etc. So I just have simple module names like xservice
and yservice
etc. Inside one such module folder, I have:
main.go
<-- package main at the topgo.mod
go.sum
/folder1
/folder1/utils.go
<- package main at the top + contains function DoSomething()
Inside main.go: how do I call DoSomething()
? vscode will not let me import it or call it, not matter what I do in terms of paths or module names. And it is part of the same module.
Please note that this question is because the example given here: https://go.dev/doc/code does not work. As in, I can't seem to get it to work in vscode with a top-level go.work
file.
Was asked for a reproducible example per comment below. I was putting it together and saw that when I use package main
everywhere, in the module, it wouldn't compile
When I followed the directory structure and reflected that in the package names per the answer below it worked (i.e. make foo.go
belong to package utils
instead).
vs code is not an IDE, it is a text editor. it happens very often, that some minor misconfiguration breaks down the whole Intellisense.
that' why i suggest to first start with reducing the amount of "View->Problems" to 0.
in go all packages are folders. for that reason i assume your IDE complains about package misconfiguration
/folder1/utils.go <- package main at the top
in my opinion utils.go
should contain package folder1
the project structure is equal the folder structure. when you use xservice
and yservice
i expect to find 2 folders with the respective names.
see an example
to achieve that, i suggest to use the power of go and not try to initialize stuff manually. when executed properly, go can generate a module for you.
when you are in a module
, you can simply access any subpackage.
the example would be like:
main.go <- package "main" at the top
go.mod <- module "whatever"
/folder1/utils.go <- package "folder1" at the top, contains function DoSomething()
then you can simply call folder1.DoSomething()
in main.
on the logic of go, you have a module
called "whatever" which has an executable main and a package
"folder1" with DoSomething
.