Home > Back-end >  Go Import alias
Go Import alias

Time:01-05

I got kinda curious about how does Golang resolves named imports.

In example here, I got Echo as a package for my app.

package main

import (
    "net/http"

    "github.com/labstack/echo/v4"
)

func main() {
    e := echo.New()
    e.GET("/", func(c echo.Context) error {
        return c.String(http.StatusOK, "Hello, World!")
    })
    e.Logger.Fatal(e.Start(":1323"))
}

As seen on the import line, Echo is actually being referenced by it's "v4" version, but Go can resolve as "echo". I've dug around Echo's Repo and couldn't find anything explicit on how does Go can resolve this.

PS: On the past I've used it with an alias, such as:

...
import (
    echo "github.com/labstack/echo/v4"
)
...

but that seems to be a workaround.

Regards!

CodePudding user response:

The first line of a Go file declares the package name using the package directive. This is the name that import resolves to when it is not an aliased import. You can use aliased imports when you need to disambiguate between multiple packages that have the same package name but different import paths.

The go.mod file keeps the import path of the Go package (for echo that is github.com/labstack/echo/v4). As JimB said, the package name does not need to correspond to the import path, it only does so by convention.

echo import

It's a good and recommended convention to use the same package name as your folder name,

But folder versioning for major releases is known and valid.

  •  Tags:  
  • go
  • Related