Modifying a struct type inside vendor files

Viewed 207

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?

2 Answers

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.

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.

Related