有没有办法追加两个go interface {} refs?

时间:2016-08-18 16:45:30

标签: go

我正在尝试创建一个方法,该方法将附加已从具有从数据库中提取的非缓存数据缓存的数据。理想情况下,执行类似下面的操作的单个方法将是理想的。那么有没有办法追加两个接口{} refs,它们都是切片?

package jmspubsubtutorial;

import javax.jms.JMSException;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.naming.Context;
import javax.naming.NamingException;

public class TopicProducer {

    public static void main(String[] args) throws JMSException, NamingException{
        System.out.println("---Starting TopicProducer---");
        Context context = TopicConsumer.getInitialContext();
        TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
        Topic topic = (Topic) context.lookup("topic/JMS_tutorial");
        TopicConnection topicConnection = topicConnectionFactory.createTopicConnection();
        TopicSession topicSession = topicConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
        topicConnection.start();
        TopicProducer topicProducer = new TopicProducer();
        String text = "message 1 from TopicProducer...";
        topicProducer.sendMessage(text, topicSession, topic);

        System.out.println("---Exiting TopicProducer---");
    }

    public void sendMessage(String text, TopicSession topicSession, Topic topic) throws JMSException {
        System.out.println("Send Message: " + text + " " + topicSession + " " + topic);
        TopicPublisher topicPublisher = topicSession.createPublisher(topic);
        TextMessage textMessage = topicSession.createTextMessage(text);
        topicPublisher.publish(textMessage);
        topicPublisher.close();
    }
}

结果https://play.golang.org/p/9cWxPg6daq

package main

import "fmt"

type foo struct {
    Name string
}

func main() {
    a := []*foo{
        &foo{"bar"},
        &foo{"boom"},
    }

    b := []*foo{
        &foo{"blam"},
        &foo{"pow"},
    }

    fmt.Println(add(a, b))
}

func add(a, b interface{}) interface{} {
    return append([]interface{}{a}, ([]interface{}{b})...)
}

期望的结果

[[0x1040a128 0x1040a130] [0x1040a140 0x1040a148]]

更新:基准

https://play.golang.org/p/9a8aZckQAF

[0x1040a128 0x1040a130 0x1040a140 0x1040a148]

2 个答案:

答案 0 :(得分:3)

仅限reflect

func add(a, b interface{}) interface{} {
    return reflect.AppendSlice(reflect.ValueOf(a), reflect.ValueOf(b)).Interface()
}

游乐场:https://play.golang.org/p/FjS73G2_G5

请注意,如果ab不兼容切片,这会让您感到恐慌。

答案 1 :(得分:1)

通常在Go中,无法将一种类型的数组转换为另一种类型的数组。您必须以特定于类型的方式执行此操作或运行for循环以转换每个元素。这是切片实现方式的结果。看到这个答案:

Type converting slices of interfaces in go

使用特定于类型的方法获得所需结果的方法如下所示: https://play.golang.org/p/RqKWvQqE_g

Go还没有" generics"虽然有些人编写的代码生成器的功能类似于Java中的泛型,但这种机制可以通过通用注释实现这一点。