【问题标题】:Different message types in one channel golang一个通道golang中的不同消息类型
【发布时间】:2022-12-07 05:56:52
【问题描述】:

我是 GO 的新手,正在尝试做这样的事情。

假设我有两种不同类型的消息要写入一个频道,

   c <- &Message1{}
   c <- &Message2{}

(我无法为每种消息类型创建两个不同的频道)

现在,我想在单独的 goroutine 中访问这两条消息。

即在Goroutine1我只想要Message1{},所以我应该只听Message1{}并忽略Message2{}频道

something := <-c
switch v := something.(type) {
case *Message1: // do something
// ignore message2
}

同样,在Goroutine2中我只想要Message2{},所以我应该只听Message2{}并忽略该频道上的Message1{}

something := <-c
switch v := something.(type) {
case *Message2: // do something 
// ignore Message1
}

有没有办法做到这一点?

【问题讨论】:

  • 你需要两个不同的渠道。您不能有选择地从频道中挑选消息。
  • “我无法为每种消息类型创建两个不同的频道”是的你可以。
  • 如果只想传递一个数据结构,请将两个通道包装在一个结构中。如果您想在本机使用发送/接收运算符,或定义SendRec 方法,请导出频道。使用泛型,您可以使此结构可重用

标签: go goroutine


【解决方案1】:

是的,您可以通过使用 interface{} 类型的通道发送消息,然后使用类型断言检查每个 goroutine 中接收到的消息的类型来实现这一点。

这是您如何执行此操作的示例:

// Define the channel that will be used to send messages
c := make(chan interface{})

// Define the two types of messages that will be sent on the channel
type Message1 struct {
    // ...
}

type Message2 struct {
    // ...
}

// In the first goroutine, you can receive messages from the channel and
// use a type assertion to check if the message is of type Message1
go func() {
    for {
        // Receive the message from the channel
        something := <-c

        // Use a type switch to check the type of the message
        switch v := something.(type) {
        case *Message1:
            // Do something with the Message1 instance
            // ...

        // Ignore any other types of messages
        default:
            continue
        }
    }
}()

// In the second goroutine, you can receive messages from the channel and
// use a type assertion to check if the message is of type Message2
go func() {
    for {
        // Receive the message from the channel
        something := <-c

        // Use a type switch to check the type of the message
        switch v := something.(type) {
        case *Message2:
            // Do something with the Message2 instance
            // ...

        // Ignore any other types of messages
        default:
            continue
        }
    }
}()

// In the main goroutine, you can send messages of type Message1 and Message2
// on the channel and they will be received by the appropriate goroutines
c <- &Message1{}
c <- &Message2{}

在此示例中,通道c 的类型为chan interface{},这意味着它可用于发送任何类型的消息。这两个 goroutine 从通道接收消息,并使用类型开关检查接收到的每条消息的类型。如果消息的类型正确,goroutine 会对其执行一些操作。否则,它会忽略该消息并继续等待下一条消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 2020-07-09
    • 2017-10-24
    • 2016-04-26
    • 1970-01-01
    相关资源
    最近更新 更多