将项目附加到函数中的切片不会更改原始切片

时间:2018-04-18 20:10:27

标签: go

有人可以解释为什么两者不相同?后者确实构建,但不能按预期工作。我认为切片会自动更改,因为它包含一个指向数组的指针。

//工作规范

func TestProcessRecords(t *testing.T) {
    var messageSent []*sqs.SendMessageInput
    w := &SQSWriter{
        queueURL: aws.String("aQueueURL"),
        service: &mock.SQS{
            SendMessageStub: func(input *sqs.SendMessageInput) (*sqs.SendMessageOutput, error) {
                messageSent = append(messageSent, input)
                return nil, nil
            },
        },
    }
    inputEvent := readFirehoseEventFromFile(t, "../../../../testdata/firehose_event.json")
    processRecords(inputEvent.Records, w)
    assert.Equal(t, 2, len(inputEvent.Records))
    assert.Equal(t, 1, len(messageSent))
}

尝试重构,因为mockedWriter将跨规格使用

//不工作规范

func mockWriter(messageSent []*sqs.SendMessageInput) *SQSWriter{
    return &SQSWriter{
        queueURL: aws.String("aQueueURL"),
        service: &mock.SQS{
            SendMessageStub: func(input *sqs.SendMessageInput) (*sqs.SendMessageOutput, error) {
                messageSent = append(messageSent, input)
                return nil, nil
            },
        },
    }
}

func TestProcessRecords(t *testing.T) {
    messageSent := []*sqs.SendMessageInput{}
    inputEvent := readFirehoseEventFromFile(t, "../../../../testdata/firehose_event.json")
    processRecords(inputEvent.Records, mockWriter(messageSent))
    assert.Equal(t, 2, len(inputEvent.Records))
    assert.Equal(t, 1, len(messageSent))
}

我应该提一下,我来自JS / Ruby / Python的背景,并且需要花一点时间来更好地掌握基础知识。

提前致谢

1 个答案:

答案 0 :(得分:1)

这是答案,所有归功于@mkopriva。

func mockWriter(messageSent *[]*sqs.SendMessageInput) *SQSWriter{
    return &SQSWriter{
        queueURL: aws.String("aQueueURL"),
        service: &mock.SQS{
            SendMessageStub: func(input *sqs.SendMessageInput) (*sqs.SendMessageOutput, error) {
                *messageSent = *append(messageSent, input)
                return nil, nil
            },
        },
    }
}

func TestProcessRecords(t *testing.T) {
    messageSent := []*sqs.SendMessageInput{}
    inputEvent := readFirehoseEventFromFile(t, "../../../../testdata/firehose_event.json")
    processRecords(inputEvent.Records, mockWriter(&messageSent))
    assert.Equal(t, 2, len(inputEvent.Records))
    assert.Equal(t, 1, len(messageSent))
}