donglaogu3788 2015-11-23 13:37
浏览 94
已采纳

从Go中的自定义类型(指针切片)中删除元素[关闭]

I have to remove an element from custom type "MergedVars" (which is a slice of pointers) while running a method of that custom type:

type Merged struct {
    Key          string
    Value        int
    Old          *Merged
}

type MergedVars []*Merged


func (m MergedVars) String() string {
    var out string

    for _, v := range m {
        out += fmt.Sprintf("Key: `%s`, Value: `%d`, Old: `%v`
", v.Key, v.Value, v.Old)
    }

    return out
}


func (m *MergedVars) Insert(key string, value int) {
    v := &Merged{
        Key:          key,
        Value:        value,
    }

    for k, mv := range *m {
        if mv.Key == key {
            v.Old = mv
            m.remove(k)
        }
    }

    *m = append(*m, v)
}


// This fails
func (m *MergedVars) remove(pos int) {
    // https://github.com/golang/go/wiki/SliceTricks
    m, m[len(m)-1] = append(m[:pos], m[pos+1:]...), nil
}

So running this...

m := MergedVars{}
m.Insert("foo", 1)
m.Insert("bar", 2)
m.Insert("foo", 3)

... should get me a slice of two elements where the element with the key "foo" has value 3 and its "old" field points to "foo": 1

See it (not) working at:

http://play.golang.org/p/0-cx8tdOZD

How do I have to implement the remove function proparly?

  • 写回答

1条回答 默认 最新

  • dsy1971 2015-11-23 14:52
    关注

    From you requirement, what I understand is that you need to replace strut whose key matches with new strut with updated value and point Old to the previous one getting replaced. One way to do as follows, where you don't need to remove from slice.

    Please note in this case your insertion order fro the new foo, 3 which is inserted after bar will not be maintained, and will be the replace the foo, 1 at position 0, before bar.

    func (m *MergedVars) Insert(key string, value int) {
        v := &Merged{
            Key:   key,
            Value: value,
        }
    
        found := false
        for k, mv := range *m {
            if mv.Key == key {
                v.Old = mv
                m1 := *m
                m1[k] = v
                found = true
            }
        }
    
        if !found {
            *m = append(*m, v)
        }
    }
    

    http://play.golang.org/p/KINvnAP08Q

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比