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

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

问题描述

我在尝试从另一个包和文件导入类型时遇到问题.我要导入的结构是下面的结构.

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 
}

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

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

pq:= &PriorityQueue{}

我像疯子一样在互联网上搜索这个简单问题的答案,但我没有找到答案.我通常用 java 编程,导入类是如此基本.

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.

推荐答案

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

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

示例导入声明:

import "container/list"

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

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"

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

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

l := m.New()

也可以这样做:

import . "container/list"

你可以完全省略包名:

l := New()

但仅在紧急情况"或出现名称冲突(很少见)时使用这些.

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

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

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