profile
viewpoint

Ask questionscmd/go: allow `go run .` in module mode without a go.mod file

What version of Go are you using (go version)?

<pre> $ go version go version go1.14beta1 linux/amd64 </pre>

Does this issue reproduce with the latest release?

Yes

What did you do?

  • Create a simple hello world project with only one main.go file.
  • Set GO111MODULE=on
  • Run go run . in the project folder.

What did you expect to see?

Run okay.

What did you see instead?

go: cannot find main module; see 'go help modules'

or for a git repository

go: cannot find main module, but found .git/config in /path/to/projects/helloworld
	to create a module there, run:
	go mod init
golang/go

Answer questions jayconrod

I'd recommend against setting GO111MODULE=on globally. That was useful for working on modules checked out into GOPATH in Go 1.12 or earlier, but since GO111MODULE=auto was changed in 1.13, I don't think it makes sense now. Maybe in a few specific cases for tools, but not generally. Hopefully people who have it set know the implications, so I wouldn't expect that tutorials need to be written for them. If any documentation recommends new users set GO111MODULE=on, we should fix that.

This specific change in behavior was #32027. In short, if a user has GO111MODULE=on set explicitly, and there's no go.mod file in the current directory or in any parent, you can only build or import packages in the standard library or packages specified as .go files on the command line. So for example, this works:

$ cat >hello.go <<EOF
package main

import "fmt"

func main() {
  fmt.Println("hello")
}
EOF

$ go run hello.go
hello

Import paths in modules other than std and cmd won't work. That includes relative imports and patterns.

$ go run
go run: no go files listed
$ go run .
go: cannot find main module; see 'go help modules'
$ go list golang.org/x/tools/gopls
can't load package: cannot find module providing package golang.org/x/tools/gopls: working directory is not part of a module
$ go list ./...
go: cannot find main module; see 'go help modules'

The rationale for this change was that early on, people would set GO111MODULE=on, not create a go.mod file, then find that everything is very slow: we need to look up module paths and versions for every import on every command, since there's nowhere to write down dependencies.

I don't think this necessarily means go build . or go run . should not work, but fixing this would probably involve adding a significant special case, and it would be risky to do that this late in the cycle.

@bcmills @matloob WDYT? We might want to do this if/when GOPATH mode is deprecated, since GO111MODULE=on will be the only mode after that.

useful!
source:https://uonfu.com/
Github User Rank List