亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 Go 中的數組返回指針數組

從 Go 中的數組返回指針數組

Go
米琪卡哇伊 2021-12-06 19:35:35
只是你知道,我對 Go 很陌生。我一直在嘗試制作這樣的功能:func PointersOf(slice []AnyType) []*AnyType{    //create an slice of pointers to the elements of the slice parameter}這就像&slice[idx]對切片中的所有元素做的一樣,但是我在如何輸入參數和返回類型以及如何創建切片本身方面遇到了麻煩。此方法需要適用于內置類型的切片,以及結構的切片和指向內置類型/結構的指針的切片調用此函數后,如果我不必強制轉換指針切片會更好編輯: 我需要這個方法的原因是有一個通用的方法來在 for ... range 循環中使用數組的元素,而不是使用該元素的副本??紤]:type SomeStruct struct {    x int}func main() {    strSlice := make([]SomeStruct, 5)    for _, elem := range strSlice {        elem.x = 5    }}這不起作用,因為 elem 是 strSlice 元素的副本。type SomeStruct struct {    x int}func main() {    strSlice := make([]SomeStruct, 5)    for _, elem := range PointersOf(strSlice) {        (*elem).x = 5    }}然而,這應該有效,因為您只復制指向原始數組中元素的指針。
查看完整描述

1 回答

?
MYYA

TA貢獻1868條經驗 獲得超4個贊

使用以下代碼循環訪問設置字段的結構片段。沒有必要創建一個指針切片。


type SomeStruct struct {

  x int

}


func main() {

  strSlice := make([]SomeStruct, 5)

  for i := range strSlice {

    strSlice[i].x = 5

  }

}

playground example


這是建議的 PointersOf 函數:


func PointersOf(v interface{}) interface{} {

  in := reflect.ValueOf(v)

  out := reflect.MakeSlice(reflect.SliceOf(reflect.PtrTo(in.Type().Elem())), in.Len(), in.Len())

  for i := 0; i < in.Len(); i++ {

    out.Index(i).Set(in.Index(i).Addr())

  }

  return out.Interface()

}

下面是如何使用它:


for _, elem := range PointersOf(strSlice).([]*SomeStruct) {

    elem.x = 5

}

playground example


查看完整回答
反對 回復 2021-12-06
  • 1 回答
  • 0 關注
  • 250 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號