Unintuitive error message for external modules that lack a go.mod

194 views
Skip to first unread message

rojiu

unread,
Oct 22, 2024, 11:39:13 AM10/22/24
to golang-nuts

I ran into this error when trying to create a module with a single Go file and import it from GitHub:

```
predeclared any requires go1.18 or later (-lang was set to go1.16; check go.mod)
```

After some digging, I learned that since Go 1.18, external modules need a go.mod file. Without one, the language spec defaults to Go 1.16. The tricky part is, it's not obvious at first glance that this error is caused by a missing go.mod file in the module you're trying to import. I was thrown off because the go.mod file in my main project had 'go 1.22.6' in it. It'll be helpful if the error message could specifically mention that it's looking for a go.mod file in the module being imported. What do you think?

Thanks!

Ian Lance Taylor

unread,
Oct 22, 2024, 1:01:56 PM10/22/24
to rojiu, golang-nuts
Thanks. Want to file a bug report at https://go.dev/issue ? Be sure
to say exactly what you did and what Go version you are using. It's
not immediately clear to me how you are importing a package that
doesn't have a go.mod file.

Ian

rojiu

unread,
Oct 22, 2024, 11:21:06 PM10/22/24
to golang-nuts
The version I'm using is go1.22.6.

To reproduce the issue, I created a repository. This repository does not contain a go.mod, but it could still be imported. Since the modules within the same repository can be used without placing a go.mod in each of them, I mistakenly thought that an external module uploaded to GitHub also wouldn’t need a go.mod.

What I tried to do was to import this external module in main.go and run it.
```
$ go mod tidy       
go: finding module for package github.com/kitsne241/samplemod
go: found github.com/kitsne241/samplemod in github.com/kitsne241/samplemod v0.0.0-20241023023417-c2f6a03a5a85

$ go run main.go
# github.com/kitsne241/samplemod
../../go/pkg/mod/github.com/kitsne241/samp...@v0.0.0-20241023023417-c2f6a03a5a85/samplemod.go:4:6: predeclared any requires go1.18 or later (-lang was set to go1.16; check go.mod)
```
main.go
```
package main

import (
"log"

"github.com/kitsne241/samplemod"
)

func main() {
date := samplemod.Date{
Day: "Sunday",
}
log.Print(date)
}

```
go.mod
```
module sample

go 1.22.6

require github.com/kitsne241/samplemod v0.0.0-20241023023417-c2f6a03a5a85
```
I felt that just finding the error message difficult to understand wasn’t enough to report it as a bug, so I posted here in case someone else had experienced the same confusion.

Thanks,

2024年10月23日水曜日 2:01:56 UTC+9 Ian Lance Taylor:
Reply all
Reply to author
Forward
0 new messages