There is a proto file

message Update { string AdminToken = 1; string Type = 2; string Hash = 3; oneof Value { string Name = 4; int64 Permission = 5; string Address = 6; } } 

I try to generate data to send to the server:

 ss := &pb.Update{Value: &pb.Update_Name{Name: "asd"}, &pb.Update_Address{Address: "s"}, &pb.Update_Permission{Permission: 12}} 

It is necessary to properly describe all three parameters in one structure. How to do it?

    1 answer 1

    It is necessary to properly describe all three parameters in one structure. How to do it?

    Your question does not relate to the declaration of the message, but rather to oneof Value .

    oneof means that the Value field will be set to one of the listed values, i.e. they are not appointed at the same time.

    Thus, after generation, we set the Value field to:

     func Test_01(t *testing.T) { v1 := Update{ Value: &Update_Name{Name: "Value1"} } t.Logf("%#v\n", v1.Value) v2 := Update{ Value: &Update_Address{Address: "Value2"} } t.Logf("%#v\n", v2.Value) v3 := Update{ Value: &Update_Permission{Permission: int64(100)} } t.Logf("%#v\n", v3.Value) } 

    Log output:

     001.pb_test.go:7: &proto.Update_Name{Name:"Value1"} 001.pb_test.go:10: &proto.Update_Address{Address:"Value2"} 001.pb_test.go:13: &proto.Update_Permission{Permission:100} 

    Perhaps you need to combine Name , Address and Permission into one structure to pass at once, then the message can be declared like this:

     syntax = "proto3"; package proto; message Update { message ValueType { string Name = 1; int64 Permission = 2; string Address = 3; } string AdminToken = 1; string Type = 2; string Hash = 3; ValueType Value = 4; } 

    Accordingly, we create as follows:

     func Test_01(t *testing.T) { v1 := Update{ Value: &Update_ValueType{ Name: "Value1", Address: "Value2", Permission: int64(100), }, } t.Logf("%#v\n", v1.Value) } 

    Log output:

     001.pb_test.go:25: &proto.Update_ValueType{Name:"Value1", Permission:100, Address:"Value2"}