jhump/protoreflect

Any method for setting nested MessageKind field

HugoNgai opened this issue · 4 comments

Hi master, I wonder if there is any way for setting a field as A MessageKind.

For example,

`message Example {
string A = 1;
string B = 2;
NestedFieldA C = 3;
}

message NestedFieldA {
string D = 1;
string E = 2;
NestedFieldB F = 3;
}

message NestedFieldB {
string G = 4;
}`

json type bytes:
var test := { "A": "test", "B": "test", "C": null }

  • Firstly, I create a dynamic Message
    msg := dynamic.NewMessage(mds)
  • Unmarshal Json to msg
    msg.UnmarshalJSON(test)

how can I dynamically set some value to NestedFieldA C or NestedFieldB F using methed msg.TrySetField?

jhump commented

@HugoNgai, you could set it using another dynamic message.

nestedFieldADesc := mds.FindFieldByName("C").GetMessageType()
nestedFieldBDesc := nestedFieldADesc.FindFieldByName("F").GetMessageType()

childMsg := dynamic.NewMessage(nestedFieldADesc)
grandchildMsg := dynamic.NewMessage(nestedFieldBDesc)

grandchildMsg.SetFieldByName("G", "a string value")
childMsg.SetFieldByName("D", "another string value")
childMsg.SetFieldByName("E", "some other string value")
childMsg.SetFieldByName("F", grandchildMsg)
msg.SetFieldByName("C", childMsg)

@jhump
cool.
Another question here.
childMsg is created by dynamic.NewMessage, which is totally a new msg struct, right?
What if some data had been Unmarshal to C, then using dynamic.NewMessage will lose those data ?

BTW, I found a method msg.Mutable from dynamicpb repo and finally solve my problem.
Is there and method like Mutable in this repo? 🤔️

jhump commented

Is there and method like Mutable in this repo?

@HugoNgai, no. In fact, you should just use the dynamicpb package. The dynamic package in this repo is effectively deprecated. See the blurb at the top of this repo's README. You can get a preview of v2 here, and you'll see there will no longer be a dynamic package.

@jhump 👌 thx!