登录
首页 >  Golang >  Go问答

动态检索 FieldDescriptor,避免硬编码字段名称(原始消息)

来源:stackoverflow

时间:2024-03-23 11:24:33 429浏览 收藏

动态检索 `FieldDescriptor` 对于避免硬编码字段名称至关重要,从而提高代码的灵活性。`protoreflect` 包提供了 `byname()`、`byjsonname()` 和 `bytextname()` 方法来获取特定字段的描述符,但这些方法需要硬编码字段名称。本文探讨了没有此限制的替代方案,以提高代码的可维护性和可靠性。

问题内容

给出以下原型消息

message mymsg {
  string my_field = 1;
  string your_field=2;
}

...protoreflect 包可用于获取每个字段的描述符

protomessage := mymsg.protoreflect()
messagedescriptor := protomessage.descriptor() // protobuf type information
fielddescriptors := messagedescriptor.fields() // list of field declarations

获取特定字段的字段描述符很简单

fielddescriptor := fielddescriptors.bytextname("my_field") // describes a field

无需对字段名称 "my_field" 进行硬编码,是否可以实现此目的?我想使用生成的代码来引用我感兴趣的领域会很好。类似(不是工作代码)

fielddescriptor := fielddescriptors.bytextname(pb.mymsg.myfield) // describes a field

这样,如果字段名称发生变化,它将在编译时捕获,甚至可以通过 ide 进行静态分析。

fielddescriptors 类型具有三种通过名称获取字段描述符的方法:

  • byname(s name)
  • byjsonname(s string)
  • bytextname(s string)

byjsonnamebytextname 都需要硬编码字段名称(作为字符串),并且 byname 接受输入为字符串的名称。结果是,我在 protoreflect 包中没有看到任何指向解决方案的内容。

上下文

字段掩码是支持部分资源更新的推荐方法。迭代字段掩码中提供的掩码很简单

protoMessage := myMsg.ProtoReflect()
messageDescriptor := protoMessage.Descriptor() // protobuf type information
fieldDescriptors := messageDescriptor.Fields() // list of field declarations

// iterate over the field paths in the field mask
for _, p := range mask.GetPaths() {

    // find the field descriptor for the field path
    fieldDescriptor := fieldDescriptors.ByTextName(p)

    if fieldDescriptor == nil {
        // field descriptor cannot be found for the field path
        return
    }

    // great, the field path points to a field, let's use it

    switch p {
    case "my_field":
        // the client wants to update MyMsg.my_field

    case "your_field":
        // the client wants to update  MyMsg.your_field
    }
}

问题是,为了实际更新 mymsg 中的正确字段,有必要在 switch 语句中硬编码字段名称。


正确答案


interface 也有 ByNumber

我假设(我没有使用该方法)您可以从您的示例中给出这个 1

还有 Get,当然这样您就可以枚举所有 FieldDescriptor。

我认为想要反映(!)生成的(结构)类型并枚举它们并不是没有道理的,但感觉就像乌龟一直向下。

如果您能提出没有所需方法就无法解决的问题,可能会有助于寻求其他答案?

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>