首页  >  文章  >  后端开发  >  以下是一些标题选项,每个标题选项都强调文章的不同方面: 聚焦问题: * 如何在 Go 1.18 中使用泛型设置不同 Firebase 消息结构中的字段? * 基因

以下是一些标题选项,每个标题选项都强调文章的不同方面: 聚焦问题: * 如何在 Go 1.18 中使用泛型设置不同 Firebase 消息结构中的字段? * 基因

Linda Hamilton
Linda Hamilton原创
2024-10-27 20:32:01720浏览

Here are a few title options, each highlighting a different aspect of the article:

Focusing on the problem:

* How to Set Fields in Different Firebase Message Structs with Generics in Go 1.18?
* Generic Function for Struct Members from External Packages:

来自外部包的结构成员的通用函数

考虑创建单个函数以将特定字段添加到不同的 Firebase 消息结构的目标,例如 Message 和 MulticastMessage,它们共享相似类型的公共字段。最初,尝试使用类型约束定义泛型函数 highPriority 时产生了错误:

<code class="go">type firebaseMessage interface {
    *messaging.Message | *messaging.MulticastMessage
}

func highPriority[T firebaseMessage](message T) T {
    message.Android = &amp;messaging.AndroidConfig{...}
    return message
}</code>

Go 1.18 的限制

在 Go 1.18 中,访问不支持类型参数的公共字段或方法。因此,这种方法失败了。

解决方案 1:类型切换

对于联合体中有限数量的类型,可以使用类型切换:

<code class="go">func highPriority[T firebaseMessage](message T) T {
    switch m := any(message).(type) {
    case *messaging.Message:
        setConfig(m.Android)
    case *messaging.MulticastMessage:
        setConfig(m.Android)
    }
    return message
}</code>

解决方案 2:使用方法进行包装

另一种方法涉及定义一个包装类型,该类型实现通用方法来设置所需的配置:

<code class="go">type wrappedMessage interface {
    *MessageWrapper | *MultiCastMessageWrapper
    SetConfig(c foo.Config)
}

// ...

func highPriority[T wrappedMessage](message T) T {
    message.SetConfig(messaging.Android{"some-value"})
    return message
}</code>

方案三:反射

对于结构体较多的场景,可以使用反射:

<code class="go">func highPriority[T firebaseMessage](message T) T {
    cfg := &amp;messaging.Android{}
    reflect.ValueOf(message).Elem().FieldByName("Android").Set(reflect.ValueOf(cfg))
    return message
}</code>

补充说明:

  • 有关类型参数限制的更多信息,请参阅[如何在接口中定义结构体字段作为类型约束?](https://go.dev/play/p/9iG0eSep6Qo)。
  • 关于实现联合约束类型的通用方法的详细信息,请访问[Go泛型中,如何使用联合约束类型的通用方法?](https://go.dev/play/p/JUHp9Fu27Yt ).

以上是以下是一些标题选项,每个标题选项都强调文章的不同方面: 聚焦问题: * 如何在 Go 1.18 中使用泛型设置不同 Firebase 消息结构中的字段? * 基因的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn