dongshao6591 2016-01-19 19:20
浏览 290
已采纳

引用库中的另一个.go文件

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 :

~/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条回答 默认 最新

  • douziqian2871 2016-01-20 04:03
    关注

    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{}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题