前往:直接附加到在地图中找到的切片 [英] Go: append directly to slice found in a map

查看:57
本文介绍了前往:直接附加到在地图中找到的切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个切片图,将值附加到相应的切片上.但是,当尝试直接附加到通过访问它返回的切片时(请参见下面的注释),它不会被存储,因此我不得不使用长格式访问(注释下方的行).

I wanted to create a map of slices where values are appended to the corresponding slice. However, when trying to append directly to the slice returned by accessing it (see comment below), it would not be stored, so I had to go with the long form access (line below the comment).

为什么会这样?我期望对地图的访问会返回某种指针,所以在我看来mappedAminoAcid == aminoAcidsToCodons[aminoAcid];显然,我错了.

Why is it so? I expected the access to the map to return some sort of pointer, so in my mind mappedAminoAcid == aminoAcidsToCodons[aminoAcid]; clearly, I'm wrong.

谢谢!

aminoAcidsToCodons := map[rune][]string{}
for codon, aminoAcid := range utils.CodonsToAminoAcid {
    mappedAminoAcid, ok := aminoAcidsToCodons[aminoAcid]

    if ok {
        // NOT WORKING: mappedAminoAcid = append(mappedAminoAcid, codon)
        aminoAcidsToCodons[aminoAcid] = append(mappedAminoAcid, codon)
    } else {
        aminoAcidsToCodons[aminoAcid] = []string{codon}
    }
}

如果基础数组必须增长以适应新元素,则

推荐答案

append返回新切片.是的,您必须将新切片放回地图中.这与字符串的工作方式没有什么不同,例如:

append returns a new slice if the underlying array has to grow to accomodate the new element. So yes, you have to put the new slice back into the map. This is no different from how strings work, for instance:

var x map[string]string
x["a"] = "foo"

y := x["a"]
y = "bar"

// x["a"] is still "foo"

要获得预期的行为,您必须使用切片指针.

To get the behaviour you expected, you'd have to use slice pointers.

aminoAcidsToCodons := map[rune]*[]string{}
for codon, aminoAcid := range utils.CodonsToAminoAcid {
    mappedAminoAcid := aminoAcidsToCodons[aminoAcid]
    *mappedAminoAcid = append(*mappedAminoAcid, codon)
}

话虽这么说,由于nil是添加的第一个完美参数,因此您可以将代码简化为

That being said, since nil is a perfectly fine first argument for append, you can simplify your code to

aminoAcidsToCodons := map[rune][]string{}
for codon, aminoAcid := range utils.CodonsToAminoAcid {
    aminoAcidsToCodons[aminoAcid] = append(aminoAcidsToCodons[aminoAcid], codon)
}

这篇关于前往:直接附加到在地图中找到的切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆