Tutorial first steps Microsoft Go - go

I am starting to learn Go following this Microsoft tutorial. The program runs and displays the result as in the tutorial, but the two problems that it is marking me cause me concern. I do not want to continue without understanding what this detail is due to, someone who has also happened to it, or who helps me to know what it is due to, I will be very grateful.
package main
import (
"fmt"
"github.com/x0z38/calculator"
"rsc.io/quote"
)
func main(){
total := calculator.Sum(3, 5)
fmt.Println(total)
fmt.Println("Version: ", calculator.Version)
fmt.Println(quote.Hello())
}
I leave you the image where the error is marked in red lines in the editor:
I leave the image of the two problems:
According to what I understood is that it does not find those files in any of the mentioned paths, but both files if I have them inside this path: C:\Projects\Go\src.
My GOPATH environment variable is: C:\Projects\Go

Golang has two ways to manage dependencies: old and new. Switching between them is usually done automatically.
Visual Sudio Code tries to check for dependencies using the old way. But I see you have go.mod and go.sum files which means you are using the new way (the Golang module system).
The environment variable GO111MODULE is used to switch between dependency control modes. It has 3 values: auto, on, off. The default is auto.
What you see is just a syntax highlighting problem and not a compilation or execution error.

What I have learned is that you want VS Code (or gopls) to correctly identify a multi-module project. Please refer to this (your are using Go1.18).
And more about go modules.
And go workspace.
Hope those can help you.

Ok this is what I did:
First: Run go mod tidy as suggested by Mushroomator in my root project, and it didn't work
Second: remove the GOPATH environment variable, since as JimB commented it is no longer used, and it didn't work either.
Now, this is where I feel a bit confused, because maybe I did what they asked me to do but I don't know how to explain it.
So, it works and no longer shows a syntax error. Delete the GOPATH environment variable, SET GOMODULE111=on, and take out the Projects/Go directory where I have all the files and put it on the desktop and mark this syntax error:
Google
Todo
Imágenes
Noticias
Shopping
Vídeos
Más
Herramientas
Cerca de 1,260,000,000 resultados (0.39 segundos)
Español
Inglés
Now, as you can see, I open VS Code directly in the helloworld directory, and the syntax error disappears, but I wanted to have it open directly from the src directory to see everything I've learned so far:

Related

go modules import for sub folder and general imports concepts understanding issues

I want to use a function from a parent module for this project https://github.com/eregnier/beuss
however (and for the repository in the current state), all my tries fails.
in my root folder I have the following go.mod file
module github.com/eregnier/beuss
go 1.17
in the ./cmd folder I have the following go.mod file
module beuss/cmd
go 1.17
I tried various combination of go.mod file for the cmd folder like
module github.com/eregnier/beuss/cmd
go 1.17
I also tried some imports from the https://github.com/eregnier/beuss/blob/main/cmd/cmd.go file looking like
import (
"fmt"
"io/ioutil"
"log"
"os"
"github.com/eregnier/beuss"
// The following line does not work either
// "github.com/eregnier/beuss" beuss
)
//try to use parent module functions
func main () {
connPUT, err := beuss.newClient(beuss.MESSAGE_PUT)
}
nothing work.
I tried the following commands desperately
go mod init
go mod tidy
go get github.com/eregnier/beuss
go install github.com/eregnier/beuss
I got the follwing errors :
go get: github.com/eregnier/beuss#v0.0.0-20220101172233-d7ecaadb1d81: parsing go.mod:
module declares its path as: beuss
but was required as: github.com/eregnier/beuss
with not understanding the real issue. I googled errors, I had a look at this which looks intersting https://go.dev/doc/code#Workspaces
In the end, I am just loosing patience for this issue where I already spend lot of time without really understanding the real good practice / why it should be done like this or that.
I am sorry if this is a redundant question. but this topic looks nebulous to me where I just want to resolve a dependency. I guess I am lost between local imports / remote imports / modules and pacakges concepts. I guess I just want an entry point to understand all of this where in javascript a simple require('../code.js') does the trick.
What I would like in the end is to be able to better understand go imports system, and pragmatically, how to solve my linked project dependency so I can use functions from parent "folder" (ideally without namespacing)
As the question was unclear because I did not understand what was wrong, I'll try here to synthetise what worked for me.
I followed andrey dyatlov advice by simply removing the go.mod from my cmd folder and It is possible to make this folder a standalone program without module management. So I can go run / build the command file.
Also I slightly changed imports system and reorganized my code folders by understanding how imports works a bit better (I did not practised go since a while and I am a relatively new commer to go world)
So for this last point, doing imports with github.com/eregnier/beuss does the trick, but I missed to export my "lib" functions by just capitalizing their name. Doing so let me import and use them elsewhere in the code.
For the next person that this question might help, it should be possible to see the state of the project (wip) from the link in the question to see how it works now.

What are the differences between CGO invocations in the main package vs a module?

I have written a BPF program that I can install using gobpf, i.e. using their bcc tooling. While this works alright from a main package, this breaks as soon as I move it into a package for importing it as a module.
To clarify: It works with all code in package main, but as soon as I rename the package and move the main() to cmd/command.go it stops working with go run complaining that it can't find an included lib (bcc/proto.h). Incidentally, this is the same error as I always got when running gcc on my .c file without any indication I want to use BPF (the part that gobpf did for me, until I moved its invocation to a module...).
I realize this is question very specific and sits in a weird place between Go, CGo, the way C and C++ handle includes, BPF, and bcc, but I am at a loss here.
You can check out my code here https://github.com/bwNetFlow/bpfdump if that helps. It needs bcc installed in addition to go run doing its thing. Basically:
HEAD is the modularized version that does not work (go run cmd/dump.go)
HEAD~ is my initial experiment that does work (go run bpfdump.go) (you'll get an permission error as user, which is fine as it has compiled anyways).
PS: I think it might have to do with this (rather creative?) construction of bcc/proto.h: https://github.com/iovisor/bcc/blob/master/src/cc/exported_files.cc

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.

Xcode shows many errors but program compiles and runs fine (in both simulator and device)

After installing the CocoaLumberjack' log compressor class I've been getting this annoying behavior: Xcode complains that there are many undeclared identifiers and gives me many errors (not warnings but errors with the red icon).
The thing is that I can compile and run my iPad app just fine but Xcode won't do any autocompletion. I tried cleaning the build folder (Product > option + Clean), and also deleting derived data. I've also rebooted to no avail.
As you can imagine this is a pain to work with. I did have this behavior happen before on a previous version of Xcode; it had something to do with stuff in my precompiled headers file but using the solution above would always fix it. I'm currently using Xcode 4.4 (4F250).
Sample error I'm getting:
Semantic Error: use of undeclared identifier 'DDTTYLogger'
The above happens even with classes that I wrote myself and that have not changed since installing the CocoaLumberjack compressor class.
I finally solved this after MANY attempts using the following:
Remove the last #import from my Prefix.pch and build again. Errors would happen (obviously). Put the line back and build again. No errors would show and after 10 seconds or so, errors would come back again.
Repeat the above except instead of the last #import, remove the last TWO imports, then three, four, etc. I did this until I removed five imports and when I put them back and waited, Xcode stopped complaining.
Note that this didn't occur to me at all. I read this solution on a blog somewhere.
Weird bug...
Open build settings and set "Precompile Prefix Header" to "No", that solved my problem.
Kudos for: https://stackoverflow.com/a/7035492/936957
I've been running into these issues constantly on all the latest versions of Xcode, in both Objective-C and Swift.
I noticed today that I was getting the errors in one particular class file. I removed it from some extra targets it was in and the errors finally went away!
I think Xcode has some fundamental bugs with it's handling of multiple targets right now. My theory is that if the other target is not built, you will essentially see errors from that target. Anyway hope this helps someone.
Not bad,
If you follow these Steps-
1-Clean Xcode(Cmd+Shif+K).
2- Clear Derived Data(Cmd+Shift+G).
Enter this path( ~/Library/Developer/Xcode/DerivedData/).
3- Quit and open again Xcode.
This problem can cause by setting "Target Membership" for some files are not the same.
Example:
A class XYZ put in file "a.swift" and it's used in file "b.swift". But "Target Membership" setting of "a.swift" is not the same "Target Membership" setting of b.swift.
Check "Target Membership" setting as below:
I was having issues with a library installed via cocoapods. Going to Build Settings and searching for 'Allow Non-modular Includes In Framework Modules' then setting it to Yes did the trick.
I had it on Xcode 10.1 when I accidentally pressed:
Cmd+Shift+U - ( build for Testing )
try Clean (Cmd+Shift+K) and then:
Cmd+Shift+R ( build for Running )
After update to Xcode 11, I met the same problem. I tried all the mentioned advices (cleaning folders, turning on/off different settings, restarting xCode), but nothing helped. Also, I have a big project in C, so, I'd like to keep using precompiled headers.
Finally I found that simple restart of Mac OS solves the problem! It's really weird behaviour, but I'm happy anyway that I found a solution – it's hard to code when lots of colourful error messages float around.
For me it helped cleanning the project. XCode->Product->Clean
I got the similar type of issue.
Alternate option to fix this is
Open organizer and delete the derived data of your project or delete all the projects in organizer projects tab. It works fine..
I just had the same thing in Xcode 5.1.
I fixed it by making sure there were no blank lines between #import's
I have removed some extra spaces and extra lines from .pch file and it xcode stopped complaining
This happened to me as well, but cleaning didn't fix it. What did was quitting and reopening XCode. Afterwards, all the phantom errors were gone. For those wondering, the tabs you have open when you close will still be open when you reopen.
I had this issue recently. It can be remedied in some cases by deleting the ModuleCache folder inside DerivedData, along with the project folder in DerivedData. Note that Xcode must be quit before doing this.
Running on Xcode Version 10.1 (10B61), I set the build setting "Increase Sharing of Precompiled Headers" to NO. I was working in an .xcworkspace with many projects sharing the same frameworks, and no Objective-C bridging header (meaning I've added no obj-c code myself). I'm not sure when Xcode did away with .pch files by default, but I didn't have any of those in my project.
Open up a terminal and create a nice little function accessible via the command line...
nano ~/.bashrc
add (making the necessary substitutions between the pointy braces)
cycle() {
git stash save "BACKUP"
git checkout <<SOME OTHER BRANCH>>
git branch -D $1
xcodebuild -allowProvisioningUpdates -workspace <<YOUR WORKSPACE>>.xcworkspace -scheme <<YOUR SCHEME>> -configuration Release clean
git checkout $1
}
^X and save it by following the prompts, then enter source ~/.bashrc to make it visible to the current terminal session.
Make sure your branch is pushed to origin, cause we're going to delete it :)
Call the function using cycle <<MY BRANCH>> (once it's run you might want to call git stash pop to restore any working copy changes)
Hope it works for you! Xcode, get on your game!
In my case (mixed objc/swift project) at least part of errors were caused by absence of imports for some used frameworks, e.g. "import UIKit". Project was compiled successfully because frameworks were anyway included in headers in Prefix.pch file. But errors were shown, for example about not finding method defined in UILabel extension, and yes, this extension was without "import UIKit". So I think these errors in most cases depends on Prefix.pch precompilation/updating.
Touching Prefix.pch, cleaning, removing derived data, closing/opening XCode sometimes helps, but not always.
Using SPM, it can be that the Module you import, which you use at the location of the errors, has missing dependencies itself.
In my case I had an error about a missing initializer, XCode trying to use a different one than the one already defined in the other Module. But the project compiled fine! Nothing worked at first. Then I tried first cleaning, and then Product -> Perform Action -> Compile "myfile.swift" and it showed what the missing dependency in the dependency was! Note: This goes recursive. In multiple places a depenendency may have not been declared in the package.swift -> compile the same file repeatedly until it compiles successfully.
So.. it wasn't that the module with the error had a missing dependency, but rather that the direct dependency did miss a Module-dependency declaration in its package.swift declaration.
My explanation is that to generate the Error-output of XCode, Modules get compiled alone on their own. Import errors then show up. But when Modules are built as part of a larger Module, then that large module may import the missing dependency of the broken sub-Module already, making the build pass.

Does Go provide REPL?

The interactive environment is VERY helpful for a programmer. However, it seems Go does not provide it. Is my understanding correct?
No, Go does not provide a REPL(read–eval–print loop).
However, as already mentioned, Go Playground is very handy. The Go Authors are also thinking about adding a feature-rich editor to it.
If you want something local, consider installing hsandbox. Running it simply with hsandbox go will split your terminal screen (with screen) where you can write code at the top and see its execution output at the bottom on every save.
There was a gotry among standard Go commands, which used to evaluate expressions (with an optional package name), and could be run like gotry 1+2 and gotry fmt 'Println("hello")' from shell. It is no longer available because not many people actually used it.
I have also seen third party projects for building a REPL for Go, but now I can only find links to two of them: igo and go-repl. How well do they work I don't know.
My two cents: Speed of compilation makes writing a REPL possible for Go, as it has also helped building the tools mentioned here, but the same speed makes REPL less necessary. Every time I want to test something in Go that I can't run in Playground I open a simple .go file and start coding and simply run the code. This will be even easier when the go command in Go 1 makes one-command build process possible and way easier.
UPDATE: Latest weekly release of Go added go command which can be used to very easily build a file: write your prog.go file and run go build prog.go && ./prog
UPDATE 2: With Go 1 you can directly run go programs with go run filename.go
UPDATE 3: gore is a new project which seems interesting.
Try motemen/gore
Yet another Go REPL that works nicely. Featured with line editing,
code completion, and more.
https://github.com/motemen/gore
You also have a recent (March 2013) project called gore from Sriram Srinivasan, which can be useful:
gore is a command-line evaluator for golang code -- a REPL without a loop, if you will.
It is a replacement for the go playground, while making it much easier to interactively try out bits of code: gore automatically supplies boiler-plate code such as import and package declarations and a main function wrapper.
Also, since it runs on your own computer, no code is rejected on security grounds (unlike go playground's safe sandbox mode).
If you're a Vim user, the vim-go plugin (https://github.com/fatih/vim-go) provides a command (GoRun) to run and print the output of the current buffer. You still have to include all the boilerplate code of a main Go file, but it still provides a convenient way to quickly test code snippets in your local environment.
Have you tried the Go Playground?
About the Go Playground
The Go Playground is a web service that runs on golang.org's servers.
The service receives a Go program, compiles, links, and runs the
program inside a sandbox, then returns the output.
The GoSpeccy project includes a builtin REPL of a restricted subset of the Go language. The implementation is using goeval.
No, but you can exploit the speed of compilation (as mentioned in other answers).
Have a look at rango that uses a generate-compile-run loop to mimic a REPL. You can also start it with imports and statements to begin an interactive session.
Gosh is the interactive Golang shell. The goal is to provide an easy-to-use interactive execution environment.
https://github.com/mkouhei/gosh
I've had some luck with the VSCode debugger, but it's fairly limited in so far as you cannot invoke function calls from the debug console Debug: Function Calls not supported #2225.
Basically you set a breakpoint after properly configuring your launch.json file. Then you can drill down on the left in the variables side bar and enter variable expressions an the debug console.
You may also like to try https://github.com/haya14busa/goplay
This enables you to run go code files from your terminal directly to the Go Playground
Please also check www.gorepl.com for go REPL and other REPLs
Go code can be run in a REPL-like way in Visual Studio Code with the Go extension and Code Runner extension. Click the Run triangle ▶ which is marked by the mouse cursor in the below screenshot to run the code and show the results in the Output pane at the bottom of Visual Studio Code.
When programming with Go Visual Studio Code will suggest additional Go extensions that can be installed to extend Visual Studio Code's functionality.

Resources