在库中引用另一个.go文件。

huangapple go评论83阅读模式
英文:

Refer to another .go file in the library

问题

我对Go语言非常陌生,我已经阅读了《如何编写Go代码》。

虽然这篇文章非常有帮助,但我对如何在同一个库中使用go文件感到困惑。

例如,这是我的目录结构:

~/src/
    hashtable/
      hashtable.go
      linkedlist.go

我想在hashtable中使用linkedlist。我的目录结构应该是什么样的,我应该使用什么包名?

英文:

I am very new to Go and I have gone through How to Write Go Code

While it was very helpful, I'm confused about how to use a go file from within the same library.

For example, this is my structure : <br>

~/src/
    hashtable/
      hashtable.go
      linkedlist.go

I want to use linkedlist in hashtable. What should be my directory structure and what package names should I use?

答案1

得分: 0

在Go语言中,具有相同包名的两个或多个文件被视为同一个包,这意味着在命名空间内可以访问所有内容,包括私有(小写字母开头)和公共(大写字母开头)的符号。

例如,如果hashtable.golinkedlist.go共享相同的包名:

package hashtable

import (
        ...
)

那么它们被视为同一个文件。

然而,如果它们有不同的包名,最佳实践是将它们放在不同的目录中。

// hashtable.go
package hashtable

import (
        ...
)

type Hashtable struct {}

// linkedlist.go
package linkedlist
import (
        ...
)

type Linkedlist struct {}

然后按照以下方式组织它们:

project/
├── hashtable
|   └── hashtable.go
└── linkedlist
    └── linkedlist.go

例如,在hashtable.go中,可以导入linkedlist以使用其公共变量:

// hashtable.go
package hashtable

import (
        ../linkedlist
)

li = linkedlist.Linkedlist{}
英文:

In Go, two or more files with the same package name are considered one package, meaning everything is accessible within the namespace, including private (lowercased) and public (capitalized) symbols.

For instance, if hashtable.go and linkedlist.go share the same package name:

package hashtable

import (
        ...
)

Then both are considered the same file.

However, if they have different package name, the best practice is to keep them in separate directory.

// hashtable.go
package hashtable

import (
        ...
)

type Hashtable struct {}

// linkedlist.go
package linkedlist
import (
        ...
)

type Linkedlist struct {}

Then organizing them this way:

project/
├── hashtable
|   └── hashtable.go
└── linkedlist
    └── linkedlist.go

And for example, in hashtable.go, import linkedlist to use its public variables:

// hashtable.go
package hashtable

import (
        ../linkedlist
)

li = linkedlist.Linkedlist{}

huangapple
  • 本文由 发表于 2016年1月20日 03:20:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/34885238.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定