[英]How to share slightly different structs between two go apps?
I'm facing a big architecture issue in my go project.我在我的 Go 项目中面临一个很大的架构问题。
database.ObjectID
data type in order to store my IDs.database.ObjectID
数据类型来存储我的 ID。 For example, here is how I would store an user in the API :type User struct {
Id primitive.ObjectId `bson:"_id,omitempty"`
Username string
Tag int
}
primitive.ObjectID
data type : the parsing to string is not automatic and it's a bit difficult to manipulate.primitive.ObjectID
数据类型不是很方便:解析为字符串不是自动的,操作起来有点困难。 So from the front point of view, the data structure would more likely look like this :type User struct {
Id string
Username string
Tag int
}
Now in order not to repeat too much code, i would like to re-use those structures from one project to the other with a third party module i would create, without having to write them all twice (one version with string
, the other with primitive.ObjectId
).现在为了不重复太多代码,我想通过我将创建的第三方模块将这些结构从一个项目重新使用到另一个项目,而不必将它们全部编写两次(一个版本带有
string
,另一个带有primitive.ObjectId
的.ObjectId )。
How can I do ?我能怎么做 ?
Create a new ID
type that is equal to interface{}
.创建一个等于
interface{}
的新ID
类型。 Then use this ID
type, casting to primitive.ObjectID
or string
when needed.然后使用此
ID
类型,在需要时转换为primitive.ObjectID
或string
。 (See example below) (见下面的例子)
type User struct {
ID ID `bson:"_id"`
}
type ID = interface{}
func main() {
u := User{
ID: primitive.NewObjectID(),
}
oid := u.ID.(primitive.ObjectID) // Cast to "primitive.ObjectID"
fmt.Println(reflect.TypeOf(oid)) // primitive.ObjectID
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.