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?
Consider the following Person struct. It has two fields – name and email – of String type. To create an instance of this struct, we use the struct expression and assign it to a mutable variable.
To create a structure, use the struct keyword and declare each of its members inside curly braces. After the declaration, specify the name of the structure variable ( myStructure in the example below): To access members of a structure, use the dot syntax (. ): myStructure.myString = "Hello World!";
It has two fields – name and email – of String type. To create an instance of this struct, we use the struct expression and assign it to a mutable variable. A mutable variable uses the mut keyword between the let keyword and the variable name.
When working with vars of the same struct definition, you can exchange the entire struct with a simple "=" assignment. C will automatically copy all of the structure elements within the struct. If they were pointers, it's the same logic because it would just be swapping/copying addresses of the struct.
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:
sampleStruct
instancesampleBoolVar
booleanThat 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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With