Import struct from another package and file golang

2019-03-11 01:16发布

问题:

I have a problem trying to import a type from another package and file. The struct that I'm trying to import is the one underneath.

type PriorityQueue []*Item

type Item struct {
   value string
   priority int   
   index int 
}

If I would put the PriorityQueue alongside with all of its methods in the same file I'd declare it with

pq:= &PriorityQueue{}

I've been searching the internet like a madman for an answer on this simple question but I have not found an answer. I usually program in java and import classes is so elementary.

回答1:

In Go you don't import types or functions, you import packages (see Spec: Import declarations).

An example import declaration:

import "container/list"

And by importing a package you get access to all of its exported identifiers and you can refer to them as packagename.Identifiername, for example:

var mylist *list.List = list.New()

// Or simply:
l := list.New()

There are some tricks in import declaration, for example by doing:

import m "container/list"

You could refer to the exported identifiers with "m.Identifiername", e.g.

l := m.New()

Also by doing:

import . "container/list"

You can leave out the package name completely:

l := New()

But only use these "in emergency" or when there are name collisions (which are rare).



回答2:

What @icza said above plus:

With Go 1.9 there are type aliases that allow you to peel off types from packages into what look like local types:

package.go contents:

type A struct {
    X, Y int
}

main.go contents:

...

import myTypes "path/to/package"

// note the equal sign
type A = myTypes.A

...