donglunzai4288 2019-03-18 20:02
浏览 137

如何row.Scan()int32进入Golang gRPC protobuf枚举字段?

// agent.proto

message Agent {
    Permission permission = 1;
    google.protobuf.Timestamp born_time = 2;

    message Permission {
        Type type = 1;

        enum Type {
            KILLNONE = 0;
            KILLALL = 1;
            DANCE = 2;
        }
   }
}

Then scanning SQL row into agent protobuf struct:

// main.go

var a proto.Agent

.....

... row.Scan(&a.Permission.Type,...)

That permission type is stored as simple MariaDB INT() value = 0 for default type. So, i can't scan it directly. So i made temp struct where Type int32 and scaned row into that temp struct after what tried to map temp struct fields to protobuf struct, but with no luck. Similar issues i had when want to scan MariaDB string values into []byte type fields but i solved that with my temp struct []byte(tmp.UUID).

What is common patterns to scan database ROW (single row) into protubuf message when non-standard protobuf field types are used?

EDIT: Does there should be some additional 0 value handling?

  • 写回答

1条回答 默认 最新

  • doulao3078 2019-03-18 22:03
    关注

    I usually work with Go types within the business domain, and use adapters to convert to/from the protobuf type.

    // Role represents a set of permissions
    type Role struct {
        KILLNONE = iota
        KILLALL
        DANCE
    }
    
    // Permission represents a set of agent permissions
    type Permission struct {
        Role Role
    }
    
    // ToProto converts a Permission Go type to a protobuf Permission
    func (p Permission) ToProto() (proto.Permission) {
        pb := proto.Permission{}
        // assign p's properties to proto's respective properties
        // with necessary type conversions.
        ...
        return pb
    }
    

    The protobuf examples usually show working with the protobuf types directly, but it seems like adapters are more common in the field.

    评论

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示