Home  >  Article  >  Backend Development  >  How Go import Path works in versioned packages

How Go import Path works in versioned packages

WBOY
WBOYforward
2024-02-14 10:21:09397browse

Go import Path 在版本化包中如何工作

Using Go language import paths in versioned packages is an important skill. With the correct import path, we can easily introduce and use packages created by other developers. However, for beginners, understanding how import paths work in versioned packages can be a bit confusing. In this article, PHP editor Baicao will explain in detail how the import path works, and provide some practical tips to help you better understand and use the import path. Whether you are a newbie or an experienced developer, this article will provide you with valuable information and guidance. let's start!

Question content

I am a little curious about how golang parses named imports.

In this example, I have echo as my application package.

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 shown in the import line, echo is actually referenced by its "v4" version, but go can resolve it to "echo". I looked into the echo repo but didn't find anything clear about how go solves this problem.

ps: I have used it with aliases in the past, like:

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

But this seems to be a workaround.

Solution

The first line of the Go file uses the package directive to declare the package name. This is the name that import resolves to when importing without an alias. Alias ​​imports can be used when you need to disambiguate between multiple packages with the same package name but different import paths.

The

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

rsc.io/quote (Source code at https://github.com/rsc/quote) Go package versioning and importing explained. You can also check out Russ Cox's blog post explaining package versioning in Go.

The above is the detailed content of How Go import Path works in versioned packages. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete