简体   繁体   中英

How can I remove an unwanted import alias in Go?

I found that very useful Go library in the web https://github.com/deckarep/golang-set that tries to port Python sets to Go.

Thanks to Visual Studio Code I eventually got it to work by importing the library import "github.com/deckarep/golang-set" and calling a function in my code:

mySet := mapset.NewSet()

VS Code automatically recognizes the alias and replaces the import directive:

import mapset "github.com/deckarep/golang-set"

However, being someone who finds those aliases confusing, I was trying to remove it but doing so, VSCode removes it from both the import statements and my code. VS Code then tells me:

undeclared name: NewSet compiler(UndeclaredName)

The package name from NewSet(...) is also package mapset . So I thought I could simply remove it. But it does not work.

I also tried to work analogously to other 3rd party packages and call the functions by the repository's name:

mySet := golang-set.NewSet()

This also leads to an error. Is the removing of the alias not possible here due to the hyphen maybe or am I overseeing something else?

Several things here:

  1. mapset is the package name. You can see this by looking at the package source code .

  2. While the import alias, in this case, is not strictly needed from a language standpoint, it's added for clarity, since the package name ( mapset ) does not match the import path ( golang-set ). Without the alias in the import statement, there's no way to tell how the package is referenced. This is why it's important for it to be there.

  3. You cannot use golang-set as your import name, becuase the - character is not permitted in an import alias. However, if you really want to, you could use golang_set or similar, by explicitly providing this as your alias:

     import golang_set "github.com/deckarep/golang-set"

    Note that this goes against naming conventions, in that packages should not have _ characters in the name. But it should still be valid.

  4. Best practice would be just to use mapset as the alias. It's the least confusing of all the available options (which is why it's automatically selected).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM