Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import struct from another package and file golang

Tags:

package

struct

go

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.

like image 612
Jakob Svenningsson Avatar asked Apr 27 '15 14:04

Jakob Svenningsson


People also ask

How do I import a struct from another package in Go?

The struct name in another package must start with a capital letter so that it is public outside its package. If the struct name starts with lowercase then it will not be visible outside its package. To access a struct outside its package we need to import the package first which contains that struct.

How do you call a function from another package in Golang?

Create a file basic.go inside the basic folder. The file inside the basic folder should start with the line package basic as it belongs to the basic package. Create a file gross.go inside the gross folder. The file inside the gross folder should start with the line package gross as it belongs to the gross package.

Can we import main package in Golang?

You cannot import the main package. Any shared code should go in a separate package, which can be imported by main (and other packages).


1 Answers

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).

like image 159
icza Avatar answered Sep 21 '22 15:09

icza