dourou9477 2018-10-12 20:14
浏览 18
已采纳

对项目使用多个软件包而不是一个软件包[关闭]

I have a basic go project structure as follows:

src/github.com/jeeves/my-project/
    |- main.go
    |- models/
        |- user.go

Contents of main.go are -

package main

var log = initializeLogger()

func main() {

    // do stuff

}

func initializeLogger() *logging.Logger {

    // build and return a logger

}

Contents of models/user.go are

package main

type User struct {
    Firstname  string    `json:"first_name"`
    Lastname   string    `json:"last_name"`
}

// other functions

I was curious about the best way to set up the package structure -

  1. Should my models/user.go be part of package models instead of package main? What's the difference and how do I know when to use either?

  2. If I do use package models, how can models/user.go access the global log object defined in the main.go? (As you can see, I'm trying to define a logger once and have it accessible throughout my app.)

Thanks!

  • 写回答

1条回答 默认 最新

  • duanbeng1923 2018-10-12 20:53
    关注

    Make a separate package for your logging API,

    Structuring your code into packages should be based on functionality, Packages should be independent of each other and their names should represent what that package is meant to be.

    If you have several models and user is one among them, and if many more model types are going to be added later, then make a package like user, customer, ..., which are sub-packages of `model.

    When import user do .../modle/user

    Similar to encoding/json.

    New packages can be added without many changes to the existing code with minimal set of changes.

    Here is a the community maintained github repository which contains project-layout information in more detail.

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

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)