在多个包之间共享结构体

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

Sharing structs across multiple packages

问题

让我们假设我们有一个客户端服务器的场景,在这种情况下,服务器和客户端使用共同的消息结构进行通信。因此,我们可以使用struct来定义消息结构,类似于以下方式:

type Message struct {
    SenderId int
    Content string
    AuthCode string
}

为了避免重复定义Message结构并在客户端包和服务器包中使用,Go语言中的解决方法是什么?

谢谢!

英文:

Lets say we have a client server scenario, in this situation both the server and the client speak to each other using a common message structure. So, one use struct to define that message structure, something like this

type Message struct {
    SenderId int
    Content string
    AuthCode string
}

Now to avoid repeating yourself and having a Message structure in both the client package and server package, what is the GoWay to address this problem ?

Thanks!

答案1

得分: 10

有三种不同的方法:

  1. 将服务器和客户端都放在同一个包中,就像http包一样。
  2. 创建单独的包(比如messagecommontypes等),并在其中添加共享的结构,就像etcd一样。
  3. 将它们放在server包中,并在client包中导入该包。例如,x/net/websocket包导入了net/http

这实际上是个人口味的问题。

英文:

There are three different approaches:

  1. Keeping both server and client in the same package, as does the
    http package.
  2. Creating separate packages (say message, common, types, ...) and adding your shared structures there, as does etcd
  3. Putting them in the server package and importing that in the client package. For example, the x/net/websocket package imports net/http.

It's really a matter of personal taste.

huangapple
  • 本文由 发表于 2015年5月24日 00:13:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/30414871.html
匿名

发表评论

匿名网友

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

确定