"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Organize a Go Project with Both a Library and a CLI in the Same Directory?

How Can I Organize a Go Project with Both a Library and a CLI in the Same Directory?

Published on 2024-12-23
Browse:710

How Can I Organize a Go Project with Both a Library and a CLI in the Same Directory?

Organizing Code in Multi-Package Projects

In Go projects that require both a library and a command-line interface (CLI), it is common to encounter the issue of having multiple packages in the same directory.

One such project structure:

whatever.io/
    myproject/
        main.go
        myproject.go

The package main and func main are essential for initiating execution in Go, while a library requires a separate package, such as package myproject. However, when importing this project, the Go compiler may object:

main.go:5:2: found packages myproject (myproject.go) and main (main.go) in $GOPATH/src/whatever.io/myproject

Solution: Nested Packages

To resolve this issue, place both packages within a new folder inside the same directory as main.go. Remember to update the import statements to reference the new package from your $GOPATH.

For example:

whatever.io/
    myproject/
        library/
            myproject.go
        main.go

In main.go, import the library package as follows:

import "../library/myproject"

This approach ensures a clear separation between the library and CLI while allowing both to reside in the same directory.

Additional Notes

  • Moving packages into a nested structure does not affect the functionality of either package.
  • go run and go build commands can be used to test and build the project.
  • Refer to the provided link for further details on the differences between go build file.go and go build.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3