How to config a simple Go project

697 Views Asked by At

I'm trying to follow the Writing an intepreter in Go book, by Thorsten Ball, and in the first chapter he establish this simple scheme

file /Users/myuser/projects/monkey/token/token.go
file /Users/myuser/projects/monkey/lexer/lexer.go
file /Users/myuser/projects/monkey/lexer/lexer_test.go

In lexer/lexer.go and lexer/lexer_test.g the files start as

package lexer

And in lexer_test.go the imports are

import (
    "testing"
    "monkey/token"
)

Then he says that for running the test, I have to run (from /Users/myuser/projects/monkey directory):

go test lexer/lexer_test.go

But when I do this, I receive the error:

lexer/lexer_test.go:6:2: cannot find package "monkey/token" in any of:
    /usr/local/opt/go/libexec/src/monkey/token (from $GOROOT)
    /Users/myuser/golang/src/monkey/token (from $GOPATH)
FAIL    command-line-arguments [setup failed]
FAIL

I've been trying to understand how to configure the packages in go, but I found a lot of very complicated documentation about GOPATH, GOROOT and go.mod. I've been trying all this approach without get rid of the issue.

Can someone help me please? I'm sure is a simple fix but I cannot figure it out :(

2

There are 2 best solutions below

2
On

As the error message says, the compiler couldn't find the package locally.

Are you sure you have installed the package?

You may need to do go get [packagename]

For e.g., go get golang.org/x/tools/cmd/goimports

0
On

For Golang, It will find package first from go root then go path then import from outside. So basically, you should have that package monkey/token in your go root or go path. I don't think it is about goimport because monkey/token didn't seem to be official lib that can be import. When I first try Golang I have the same problem. I solve by create that package in go path (your working dir) or create that package from your book.