I’ve been having a hard time trying to execute a simple golang program in a virtual machine powered by vagrant.
These are the relevant fields of my go env
:
GOARCH="amd64"
GOPATH="/usr/local/src/go"
GOROOT="/usr/local/go"
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
This is the program I’m trying to execute ( located in /usr/local/src/go/program ):
package program
import (
"fmt"
)
func main() {
fmt.Print("Aloha")
}
This, the output that I get:
main.go:4:5:
/usr/local/go/src/fmt/doc.go:1:1: expected 'package', found 'EOF'
package runtime:
/usr/local/go/src/runtime/alg.go:1:1: expected 'package', found 'EOF'
Take into account that this is a completely fake program. The weird thing is that it totally works in a different environment.
What am I missing here?
Thanks a lot!
asked Jun 29, 2015 at 7:36
7
Using VS Code for GO, and faced the same issue.
Saving the file ‘Ctrl+S’ on Windows fixed the issue.
Reference :
Answered by Nico
answered Mar 2, 2018 at 11:10
Code_YogaCode_Yoga
2,9386 gold badges30 silver badges49 bronze badges
5
This usually happens when you have a file e.g. foo_test.go empty or without package declaration.
answered Aug 7, 2016 at 8:50
1
Just save the file first and than run the cammand.it is working.
go run main.go
answered Sep 23, 2019 at 7:10
JavedJaved
3973 silver badges6 bronze badges
1
The problem wasn’t neither with GOROOT
nor GOPATH
. The go installation failed at some point, leaving the whole thing unstable ( files created but completely empty ). When provisioning the virtual machine again, the go module checked whether the files existed. As they did, it took by granted that the installation had already take place.
A clean up and fresh installation from scratch solved the problem.
answered Jun 29, 2015 at 9:20
ThisIsEricoThisIsErico
1,8652 gold badges19 silver badges24 bronze badges
0
With gopls (v0.4.0 at the time of writing, so pretty unstable!) and vscode doing cmd+shift+P > Go: Restart language server
worked for me.
answered Apr 20, 2020 at 16:02
LukeLuke
2,1721 gold badge30 silver badges41 bronze badges
3
I have faced exactly same issue today while running golang
in vscode
.
Error
This usually happen when you don’t save code and run code directly thinking IDE like Intellij does autosave for us, but in vscode you can enable autosave to avoid this kind of error and save some time.
Go to File -> Auto save
answered May 24, 2021 at 8:55
kriskris
91910 silver badges15 bronze badges
0
A separate Go file in the same package,didn’t have the «package main» declaration
and because of this the console was giving errors on running the Main GO file.
On providing the package main declaration to the other Go file ,the error stopped showing.
answered Aug 18, 2019 at 14:42
srt111srt111
1,00911 silver badges19 bronze badges
2
For me, this also happened using Atom + Go Plus + Terminal Plus. The problem was that leading bracket was not on the «correct» line.
NOTE: Go Plus warns about syntax upon save, but I had imported this file after creating it locally with VIM, so I was never presented with the lint errors…
Error:
package main
import "fmt"
func main()
{
fmt.Println("hello world")
}
Correct:
package main
import "fmt"
func main() {
fmt.Println("hello world")
}
answered Feb 28, 2017 at 4:14
tdensmoretdensmore
6581 gold badge6 silver badges19 bronze badges
In my case, go.mod was caching the older version of it also. causing file to not save itself.
resolved the conflict locally. and did a File -> Auto Save
answered Nov 21, 2022 at 11:26
sumityasumitya
2,6111 gold badge19 silver badges31 bronze badges
If this issue occurs on hitting Ctrl+S after commenting the entire code,
Just uncomment package <package_name>
line and hit Ctrl+S. Issue resolves
answered Dec 29, 2022 at 13:12
karthikeyankarthikeyan
1951 silver badge10 bronze badges
In my case i was solve the problem by Using «VS Code» instead of default «text editor»
The problem was some extra characters present in the file. Once we remove extra characters it will work.
I wish it will solve to you also.
answered Oct 29, 2020 at 1:56
As said by already suggested by Nico, When you create a new project and new main.go file this error will appear when the file is not saved. Save the file (ctrl + s) and this error will disappear in both mac & windows.
I faced the same issue and just got it resolved by doing ctrl+S on the main.go file.
answered Dec 26, 2018 at 20:37
sonu1986sonu1986
2113 silver badges4 bronze badges
just remember to Ctrl save before running your program and you are all good to go
answered Jun 21, 2022 at 8:38
In my case it was empty main.go
file.
I have small http server with following file structure:
├── cmd
│ └── server
│ └── main.go
└── internal
└── server
├── http.go
├── log.go
└── main.go <--- this one was empty
While running server with go run ./cmd/server/main.go
server referenced to internal
package and it was the reason for: expected 'package', found 'EOF'
.
Removing internal/server/main.go
fixed the issue.
answered May 15 at 2:47
zooblinzooblin
2,0922 gold badges26 silver badges33 bronze badges
As a new go user I came upon this answer looking for someone to tell me that I need to start my scripts with package main
although my error was a little different,
… expected 'package', found 'import'
It’s real obvious now, but hey, that’s how it goes.
answered Jul 5, 2017 at 4:35
kpiekpie
9,4685 gold badges28 silver badges49 bronze badges
Comments
jhaumont
changed the title
affected/package: cmd/go — modindex — Can’t install delve with go 1.19
cmd/go — modindex — Can’t install delve with go 1.19
Aug 24, 2022
jhaumont
changed the title
cmd/go — modindex — Can’t install delve with go 1.19
cmd/go — modindex: Can’t install delve with go 1.19
Aug 24, 2022
dr2chase
added
the
NeedsInvestigation
Someone must examine and confirm this is a valid issue and not a duplicate of an existing one.
label
Aug 24, 2022
bcmills
changed the title
cmd/go — modindex: Can’t install delve with go 1.19
cmd/go: error installing delve with go 1.19 with module indexing enabled
Aug 25, 2022
bcmills
added
the
WaitingForInfo
Issue is not actionable because of missing required information, which needs to be provided.
label
Sep 8, 2022
bcmills
removed
the
WaitingForInfo
Issue is not actionable because of missing required information, which needs to be provided.
label
Sep 19, 2022
bcmills
changed the title
cmd/go: error installing delve with go 1.19 with module indexing enabled
cmd/go: expected 'package', found 'EOF'
errors with module indexing enabled on WSL2
Sep 29, 2022
Problem Description:
I’ve been having a hard time trying to execute a simple golang program in a virtual machine powered by vagrant.
These are the relevant fields of my go env
:
GOARCH="amd64"
GOPATH="/usr/local/src/go"
GOROOT="/usr/local/go"
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
This is the program I’m trying to execute ( located in /usr/local/src/go/program ):
package program
import (
"fmt"
)
func main() {
fmt.Print("Aloha")
}
This, the output that I get:
main.go:4:5:
/usr/local/go/src/fmt/doc.go:1:1: expected 'package', found 'EOF'
package runtime:
/usr/local/go/src/runtime/alg.go:1:1: expected 'package', found 'EOF'
Take into account that this is a completely fake program. The weird thing is that it totally works in a different environment.
What am I missing here?
Thanks a lot!
Solution – 1
The problem wasn’t neither with GOROOT
nor GOPATH
. The go installation failed at some point, leaving the whole thing unstable ( files created but completely empty ). When provisioning the virtual machine again, the go module checked whether the files existed. As they did, it took by granted that the installation had already take place.
A clean up and fresh installation from scratch solved the problem.
Solution – 2
This usually happens when you have a file e.g. foo_test.go empty or without package declaration.
Solution – 3
For me, this also happened using Atom + Go Plus + Terminal Plus. The problem was that leading bracket was not on the “correct” line.
NOTE: Go Plus warns about syntax upon save, but I had imported this file after creating it locally with VIM, so I was never presented with the lint errors…
Error:
package main
import "fmt"
func main()
{
fmt.Println("hello world")
}
Correct:
package main
import "fmt"
func main() {
fmt.Println("hello world")
}
Solution – 4
As a new go user I came upon this answer looking for someone to tell me that I need to start my scripts with package main
although my error was a little different,
… expected 'package', found 'import'
It’s real obvious now, but hey, that’s how it goes.
Solution – 5
Using VS Code for GO, and faced the same issue.
Saving the file ‘Ctrl+S’ on Windows fixed the issue.
Reference :
Answered by Nico
Solution – 6
As said by already suggested by Nico, When you create a new project and new main.go file this error will appear when the file is not saved. Save the file (ctrl + s) and this error will disappear in both mac & windows.
I faced the same issue and just got it resolved by doing ctrl+S on the main.go file.
Solution – 7
A separate Go file in the same package,didn’t have the “package main” declaration
and because of this the console was giving errors on running the Main GO file.
On providing the package main declaration to the other Go file ,the error stopped showing.
Solution – 8
Just save the file first and than run the cammand.it is working.
go run main.go
Solution – 9
With gopls (v0.4.0 at the time of writing, so pretty unstable!) and vscode doing cmd+shift+P > Go: Restart language server
worked for me.
Solution – 10
In my case i was solve the problem by Using «VS Code» instead of default «text editor»
The problem was some extra characters present in the file. Once we remove extra characters it will work.
I wish it will solve to you also.
Solution – 11
I have faced exactly same issue today while running golang
in vscode
.
Error
This usually happen when you don’t save code and run code directly thinking IDE like Intellij does autosave for us, but in vscode you can enable autosave to avoid this kind of error and save some time.
Go to File -> Auto save
Solution – 12
just remember to Ctrl save before running your program and you are all good to go
Solution – 13
In my case, go.mod was caching the older version of it also. causing file to not save itself.
resolved the conflict locally. and did a File -> Auto Save
Loading
Мне было трудно выполнить простую программу golang на виртуальной машине, работающей на vagrant.
Это соответствующие поля моего go env
:
GOARCH="amd64"
GOPATH="/usr/local/src/go"
GOROOT="/usr/local/go"
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
Это программа, которую я пытаюсь выполнить (находится в / usr / local / src / go / program):
package program
import (
"fmt"
)
func main() {
fmt.Print("Aloha")
}
Вот результат, который я получаю:
main.go:4:5:
/usr/local/go/src/fmt/doc.go:1:1: expected 'package', found 'EOF'
package runtime:
/usr/local/go/src/runtime/alg.go:1:1: expected 'package', found 'EOF'
Учтите, что это полностью фейковая программа. Странно то, что он полностью работает в другой среде. Что мне здесь не хватает?
Большое спасибо!
10 ответов
Лучший ответ
Проблема не была ни в GOROOT
, ни в GOPATH
. В какой-то момент установка go завершилась неудачно, в результате все работало нестабильно (файлы были созданы, но полностью пусты). При повторной инициализации виртуальной машины модуль go проверил, существуют ли файлы. Когда они это сделали, само собой разумеется, что установка уже состоялась.
Очистка и новая установка с нуля решили проблему.
12
ThisIsErico
29 Июн 2015 в 09:20
Как новый пользователь go, я наткнулся на этот ответ, ища кого-нибудь, кто сказал бы мне, что мне нужно запускать свои скрипты с package main
, хотя моя ошибка была немного другой,
… expected 'package', found 'import'
Сейчас это действительно очевидно, но, эй, вот как это происходит.
-2
kpie
5 Июл 2017 в 04:35
В моем случае я решил проблему, используя «VS Code» вместо по умолчанию «текстовый редактор»
Проблема заключалась в том, что в файле присутствовали некоторые лишние символы. Как только мы удалим лишние символы, все заработает.
Я хочу, чтобы это решило и вам.
0
Muthulakshmi M
29 Окт 2020 в 01:56
Как уже было сказано Нико, когда вы создаете новый проект и новый файл main.go, эта ошибка появляется, когда файл не сохраняется. Сохраните файл (ctrl + s), и эта ошибка исчезнет как в Mac, так и в Windows. Я столкнулся с той же проблемой, и я просто решил ее, нажав ctrl + S в файле main.go.
0
sonu1986
26 Дек 2018 в 20:37
отдельный файл Go в том же пакете, не имел декларации «основной пакет» из-за этого консоль выдавала ошибки при запуске главного файла GO .
При предоставлении основного объявления пакета другому файлу Go ошибка перестала отображаться.
2
starzar
18 Авг 2019 в 14:42
Для меня это также произошло с использованием Atom + Go Plus + Terminal Plus. Проблема заключалась в том, что ведущая скобка находилась не на «правильной» строке.
ПРИМЕЧАНИЕ : Go Plus предупреждает о синтаксисе при сохранении, но я импортировал этот файл после его локального создания с помощью VIM, поэтому я никогда не сталкивался с ошибками lint …
Ошибка:
package main
import "fmt"
func main()
{
fmt.Println("hello world")
}
Верный:
package main
import "fmt"
func main() {
fmt.Println("hello world")
}
3
tdensmore
28 Фев 2017 в 04:14
С gopls (v0.4.0 на момент написания, настолько нестабильно!) И vscode выполнение cmd+shift+P > Go: Restart language server
у меня сработало.
6
Luke
20 Апр 2020 в 16:02
Просто сначала сохраните файл, а затем запустите cammand. Он работает.
Иди, беги main.go
16
Javed
23 Сен 2019 в 07:10
Обычно это происходит, когда у вас есть файл, например. foo_test.go пустой или без объявления пакета.
25
Alessandro Resta
7 Авг 2016 в 08:50
Используя VS Code для GO, столкнулся с той же проблемой. Сохранение файла Ctrl + S в Windows устранило проблему.
Справка :
Ответил автор: Нико
58
Code_Yoga
2 Мар 2018 в 11:10