英文:
Modifying a struct type inside vendor files
问题
我必须修改一个供应商文件中的结构体。假设结构体在供应商文件中的样子是这样的:
type sampleStruct struct {
sampleStringvar1 string
sampleStringvar2 string
}
我需要添加一个字段,像这样:
type sampleStruct struct {
sampleStringvar1 string
sampleStringvar2 string
sampleBoolVar bool
}
我该如何实现这个目标?修改供应商变量是否是一个好的做法?如果不是,有什么更好的方法来实现这个目标?
英文:
I have to modify a struct inside a vendor file. Suppose this is how the struct is inside the vendor file
type sampleStruct struct {
sampleStringvar1 string
sampleStringvar2 string
}
I need to add one more field to it like this
type sampleStruct struct {
sampleStringvar1 string
sampleStringvar2 string
sampleBoolVar bool
}
How can I achieve this? Is it good practise to modify vendor variables like this? If not what is the best way to do this?
答案1
得分: 6
如果您不想分叉一个供应商库并用自己的库替换它,最佳做法是在您的项目中使用一个包装器。
包装器对象将是一个结构体:
- 引用一个
sampleStruct
实例 - 具有一个
sampleBoolVar
布尔值
即:
type MySampleStruct {
ss *sampleStruct
sampleBoolVar bool
}
这样,您可以在供应商库继续使用sampleStruct
的同时,又可以从sampleBoolVar
中受益。
但是,blackgreen在评论中指出:
> 如何在其自己的包之外引用一个未导出的结构体,就像sampleStruct
一样?
这是正确的,上述建议不是关于公开一个私有变量,而是根据您从sampleStruct
中观察到的内容来管理该变量。
根据库的行为,这可能是不可能的。
英文:
If you don't want to fork a vendored library and replace it with your own, the best practice would be, in your project, to use a wrapper.
The wrapper object would be struct:
- referencing a
sampleStruct
instance - with a
sampleBoolVar
boolean
That is:
type MySampleStruct {
ss *sampleStruct
sampleBoolVar bool
}
That way, you can benefit from sampleBoolVar
while the vendored library keep using a sampleStruct
as usual.
But, blackgreen points out in the comments:
> How would you be able to reference an unexported struct, as sampleStruct
appears to be, outside its own package?
This is correct, and the aforementioned suggestion is not about exposing a private variable, but about managing that variable yourself, based on what you see from sampleStruct
.
Depending on the library behavior, that might not be possible.
答案2
得分: 3
修改供应商变量是否是一个好的做法?
绝对不是。
如果不是的话,最好的方法是什么?
分叉供应商模块,并在你的 go.mod
文件中使用 replace
指令引用该分叉。
英文:
> Is it good practise to modify vendor variables like this?
Absolutely not.
> If not what is the best way to do this?
Fork the vendor module and reference the fork with a replace
directive in your go.mod
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论