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

huangapple go评论78阅读模式
英文:

Change pointer to slice of type to another slice of another type

问题

var buf1 []Somestruct1
var buf2 []Somestruct2

var selected_buf interface{} // 需要声明为接口类型
changeme := 0
switch changeme {
case 0:
    // 应该指向 buf1 以便在将来进行修改
    selected_buf = &buf1
case 1:
    // 应该指向 buf2 以便在将来进行修改
    selected_buf = &buf2
}

// 使用和修改的示例
len := len(selected_buf.([]Somestruct1)) // 获取长度
selected_buf = append(selected_buf.([]Somestruct1), Somestruct1{}) // 根据指针选择 Somestruct1 或 Somestruct2 进行追加

我想重构一些代码,但是由于指针的问题,无论我选择如何实现,都会出现各种错误。之前类似这样的代码是可以工作的:

var newstruct Somestruct3
for i := range buf1 {
    current := buf1[i]
    if current.somefield == someint {
        newstruct.somefield = &current
    }
}

它可以正常工作。我不知道该怎么办。请帮帮我)

"版主,请友善一点 - 我正在使用网络差的手机打字。谢谢"

英文:
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

<br/>
I want to refactor some code, but cannot do it because the pointer gaves me variety of errors depending on how I choose to implement it. Previously something like that worked:

var newstruct Somestruct3
for i := range buf1 {
    current := buf1[i]
    if current.somefield == someint {
        newstruct.somefield = &amp;current
    }
}

And it worked fine. idk what to do. pls help)

"moderators, please, be kind - I'm typing from the phone on the shitty network. thanks"

答案1

得分: 3

根据我所看到的,这两种类型将被合并为一种类型,因此可以进行的一种可能的工作是引入一个接口,并将可能的方法附加到该接口上。

type testinterface interface {
}

func main() {
    var tmp []Somestruct1
    var tmp2 []Somestruct2
    var tmp3 []testinterface

    tmp3 = append(tmp3, &Somestruct1)
    tmp3 = append(tmp3, &Somestruct2)
}
英文:

As I see these two types are going to be merged into one type, so one possible work that can be done is to introduce an interface with possible methods and append it to that interface

type testinterface interface {
}

func main() {
	var tmp []Somestruct1
	var tmp2 []Somestruct2
	var tmp3 []testinterface

	tmp3 = append(tmp3, &amp;Somestruct1)
	tmp3 = append(tmp3, &amp;Somestruct2)
}

huangapple
  • 本文由 发表于 2023年3月31日 09:48:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75894219.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定