douyi1982 2016-02-23 11:28
浏览 222
已采纳

有没有在golang包之间共享结构的有效方法?

I have a short program in Go with the following files part of it. Program directory structure:

myprogram/
    main.go
    server.go
    routines.go
    structs.go

These different files contain different function. The structs.go file contains a list of structure type defined, and used in several files of my program. What I want to do, now is to split my program into package like in this example :

main/
    main.go // the main program
server/
    server.go // a package imported in main
routines/
    routines.go // a package imported in main

My problem, is that I do not know where to put structs.go because it contains structures used in several package, as in the 'main.go' code.

How to share efficiently this structs.go file ? Should I include it (via a symlink to the file) in each of the package I defined, i.e serverand routines and also in main ?

My method may be awkward because I'm a beginner in Go, and in programming generally.

  • 写回答

1条回答 默认 最新

  • douyu1990 2016-02-23 11:40
    关注

    Don't link files across packages, that's bad practice. For one, the code will be duplicated. For another, identifiers will be duplicated meaning to denote the same entities (e.g. type or function), but they will be distinct. E.g. if linked and structs.go would contain a type Response definition, you would have 2 distinct types server.Response and routines.Response giving just more confusion.

    One solution would be to put structs.go into its own package, e.g. model, and all other packages relying on it can import it (e.g. your main, server and routines).

    In a theoretical example: if package A imports package B and structs.go would be needed in both, then it could also be added to package B. If there would be a package C needing only structs.go, then again it would be wiser to create its own package model (so package C doesn't need to import / know about package B, only the new model package).

    Also if noone else will use your package and it is not too complex, it might not worth the hassle to organize it into multiple packages.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 GD32 SPI通信时我从机原样返回收到的数据怎么弄?
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?