英文:
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
有三种不同的方法:
- 将服务器和客户端都放在同一个包中,就像
http包一样。 - 创建单独的包(比如
message、common、types等),并在其中添加共享的结构,就像etcd一样。 - 将它们放在
server包中,并在client包中导入该包。例如,x/net/websocket包导入了net/http。
这实际上是个人口味的问题。
英文:
There are three different approaches:
- Keeping both server and client in the same package, as does the
httppackage. - Creating separate packages (say
message,common,types, ...) and adding your shared structures there, as doesetcd - Putting them in the
serverpackage and importing that in theclientpackage. For example, thex/net/websocketpackage importsnet/http.
It's really a matter of personal taste.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论