将指向类型切片的指针更改为另一种类型的另一个切片

问题描述 投票:0回答:1
var buf1 []Somestruct1
var buf2 []Somestruct2

var selected_buf //pointer, needs to be declared. I used *int, []interface{}, *[]interface{}, but nothing seems to work so far

changeme := 0
switch changeme {
    case 0:
        // should point to buf1 to mutate it in future
        selected_buf = &buf1
    case 1:
        // should point to buf2 to mutate it in future
        selected_buf = &buf2
}

// examples of use and mutation
len(selected_buf)
selected_buf = append(selected_buf, Somestruct1) // or Somestruct2 depending on pointer

我想重构一些代码,但无法做到,因为根据我选择的实现方式,指针会给我带来各种错误。以前类似的东西有效:
var newstruct Somestruct3
for i := range buf1 {
    current := buf1[i]
    if current.somefield == someint {
        newstruct.somefield = &current
    }
}

而且效果很好。我不知道该怎么办。请帮助)

“版主,请善待 - 我正在通过糟糕的网络电话打字。谢谢”

go pointers slice
1个回答
0
投票

原来 buf1 和 buf2 是深度连接的。我试图从一个切片中删除元素,并选择我应该从哪个切片中删除它。尽管如此,我还是不得不删除字段中具有相同 int 的结构(Somestruct1 具有 ID 字段,Somestruct2 在其中一个字段中具有相同的 ID)。所以我只是循环嵌套它。当在 buf1[Somestruct1].ID 中找到 ID - 只需遍历 buf2[Somestruct2].ID 并将其删除。然后,删除 buf1[Somestruct1].
换句话说 - 你不能以任何方式覆盖静态类型的语言。我尝试过使用接口切片,但是不,不起作用。

© www.soinside.com 2019 - 2024. All rights reserved.