只是你知道,我對 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
- 1 回答
- 0 關注
- 250 瀏覽
添加回答
舉報
0/150
提交
取消