从另一个包和文件golang导入结构体 [英] Import struct from another package and file golang

查看:1506
本文介绍了从另一个包和文件golang导入结构体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图从另一个包和文件中导入一个类型时遇到问题。

 类型PriorityQueue [] * Item 

type Item struct {
value string
priority int
index int
}

如果我将PriorityQueue与其所有方法放在同一个文件中,我会用

  pq:=& PriorityQueue {} 

我一直在寻找互联网疯子在这个简单的问题上的答案,但我还没有找到答案。我通常使用java编程,导入类是如此简单。

解决方案

在Go中,您不要导入类型或函数,而是导入 packages (参见规范:导入声明)。



示例导入声明:

  importcontainer / list

通过导入一个包你可以访问它的所有导出标识符,您可以将它们称为 packagename.Identifiername ,例如:

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

//或简单地说:
l:= list.New()

在导入声明中有一些技巧,例如:

  import mcontainer / list

您可以使用m.Identifiername引用导出的标识符,例如

  l:= m.New()

另外做:

  import。 container / list

您可以完全忽略包名:

  l:=新()



<但只能使用这些在紧急情况下或有名称冲突(很少见)。


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.

解决方案

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

这篇关于从另一个包和文件golang导入结构体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆