Run code with multiple files in the same main package in GoLang

English 简体中文 繁体中文 ภาษาไทย Tiếng Việt
Summary

When developing Go programs with multiple files within the same main package, directly running `go run main.go` will fail to resolve symbols defined in other source files. To successfully execute such a program, especially when not within the GOPATH, developers have a few effective methods. On *nix systems, `go run *.go` can load all necessary files, though this command is not functional on Windows due to shell expansion differences. A more universal solution is `go run .`, which correctly processes all Go files in the current directory across all operating systems. Alternatively, `go build` generates a standalone executable binary, offering a convenient way to run the program directly after compilation.

ในการรันโปรแกรม GoLang จะต้องมีฟังก์ชัน main() ที่กำหนดไว้ ในบางกรณีเมื่อพัฒนาโปรแกรมสาธิตที่มีหลายไฟล์และต้องการใส่ไว้ในแพ็กเกจ main เดียวกัน และโฟลเดอร์นี้ไม่ได้อยู่ใน GOPATH จะรันโปรแกรมอย่างไร

สมมติว่าเรามีโครงสร้างโฟลเดอร์ดังต่อไปนี้ โดยที่ฟังก์ชัน main() ถูกกำหนดไว้ใน main.go

หากคุณเพียงแค่รันคำสั่งด้านล่าง โปรแกรมจะไม่สามารถเริ่มทำงานได้และจะแสดงข้อผิดพลาดหากมีการกำหนด struct บางอย่างในไฟล์อื่นและถูกใช้งาน

PS D:\Project\Go\sourcecode_updater\v2> go run main.go
# command-line-arguments
.\main.go:35:11: undefined: Pool
.\main.go:76:12: undefined: UpdateJob

มีหลายวิธีในการรันโปรแกรมให้สำเร็จ

go run *.go

ในระบบปฏิบัติการ *nix บางระบบ รวมถึง Linux และ MacOS สามารถรัน go run *.go ซึ่งจะโหลดไฟล์ go ทั้งหมดในแพ็กเกจและรัน main()

แต่คำสั่งนี้ใช้ไม่ได้บน Windows เนื่องจาก token expansion ไม่ทำงานใน command line ของ Windows

PS D:\Project\Go\sourcecode_updater\v2> go run *.go
CreateFile *.go: The filename, directory name, or volume label syntax is incorrect.

go run .

คล้ายกับคำสั่งด้านบน คำสั่งนี้จะพยายามโหลดไฟล์ทั้งหมดในโฟลเดอร์ปัจจุบันและรันฟังก์ชัน main() และสามารถทำงานได้บน Windows เช่นกัน

PS D:\Project\Go\sourcecode_updater\v2> go run .
all workers started
2021/05/15 23:15:54 start fetching posts to process
2021/05/15 23:15:54 start to process batch 1

go build

GoLang มีวิธีที่สะดวกและรวดเร็วในการสร้างไบนารีที่สามารถเรียกใช้งานได้ เพื่อให้สามารถรันได้ง่ายด้วยคำสั่ง go build

PS D:\Project\Go\sourcecode_updater\v2> go build -o main.exe
PS D:\Project\Go\sourcecode_updater\v2> ./main
all workers started
2021/05/15 23:17:29 start fetching posts to process
2021/05/15 23:17:29 start to process batch 1

นี่คือความสวยงามของ GoLang

GOLANG EXECUTABLE MAIN PACKAGE MULTIPLE FILE

  RELATED

  COMMENTS

0

No comment for this article.