ygot icon indicating copy to clipboard operation
ygot copied to clipboard

Getting the value of a union

Open ianbarrere opened this issue 1 year ago • 3 comments

Once a union value is set, is it possible to get the value it was set to again as a "standard" type without marshalling to JSON?

I'm working with NetworkInstance_Protocol_Ospfv2_Area_Identifier_Union, which is a union of string and uint32. Let's say I set it like this:

ospf := &ocNetInst.NetworkInstance_Protocol_Ospfv2{}
area, _ := ospf.NewArea(ocNetInst.UnionUint32(10))

I would like to retrieve the value of area.Identifier as a uint32 of 10 elsewhere in my code, but nothing I try works, because this variable is of type NetworkInstance_Protocol_Ospfv2_Area_Identifier_Union, and I haven't found anything in ygot that will give us back the value. I am also relatively new to go, so I might be missing something obvious about converting values as well.

ianbarrere avatar Dec 04 '24 21:12 ianbarrere

I was able to work around this by using fmt.Sprintf() to force the value into a string like so:

ospf := &ocNetInst.NetworkInstance_Protocol_Ospfv2{}
area, _ := ospf.NewArea(ocNetInst.UnionUint32(10))
areaIdString := fmt.Sprintf("%v", area.Identifier)

It prints it with an & and wrapped in {}, but I can strip those out, so it's better than nothing.

ianbarrere avatar Dec 16 '24 21:12 ianbarrere

Sorry -- yes, this is ugly. We generate a getter for this leaf if you use -generate_leaf_getters which allows you to do area.GetIdentifier() but we don't do anything special for union leaves... :-(

If you want to get this value back, do you already know what the type that you have set it to is? For example, could we improve this by generating something like the getters that proto does for oneof fields? This would look something like v, err := area.GetIdentifier_Uint32() and would return uint32. We'd have to return an error in cases where you specified the wrong type.

If you didn't know the type, we could (thinking about it as I type) do something like:

v, ok := area.GetIdentifier_Uint32()
if !ok {
  // handle a non-uint32 type
}

which seems quite idiomatic for a type assertion.

robshakir avatar Dec 18 '24 03:12 robshakir

Hi Rob,

Thanks for the info. In my particular situation I do know what type it will be, so the first solution would be quite suitable. In any case, handling different types with the val, ok syntax seems good as well.

Ian

ianbarrere avatar Dec 18 '24 09:12 ianbarrere