Amid
Amid

Reputation: 621

How to have custom String method in Protocol Buffer?

Let's say I have a proto file like:

message Sample {
  Test t = 1;
}

message Test {
  string s = 1;
}

I want to have my own customize String method on type Test, but since the auto generated code of protoc already includes String method, my custom String method leads to a compiler error.

It is worth mentioning the auto generated String method is:

func (x *Test) String() string {
    return protoimpl.X.MessageStringOf(x)
}

The above code, just prints the value itself but I was wondering if there is any way which I can use my custom String implementation?

Upvotes: 3

Views: 1887

Answers (2)

keser
keser

Reputation: 2642

I don't think you should mess around with generated pb files and use a wrapper struct instead.

type Wrapper struct{
   pb.Sample
}

func (w Wrapper) String() string{
  ...
}

Second option that comes to my mind is that maybe you can write a plugin for protoc and make it use those methods when needed struct tag is given.

Upvotes: 4

Rajvir
Rajvir

Reputation: 108

You can replace the implementation in the *.pb.go file itself. However, the change will be gone if the original proto file is compiled at the same path where the modified file is.

Upvotes: -2

Related Questions