英文:
Replace methode for a custom type array in golang
问题
我正在尝试在一个自定义类型中添加或替换(或添加)一个字段,该字段仅是基于结构体的数组。基本上是一些简单的东西,请看这里:
https://play.golang.org/p/Fb04g4Oq1C
我在第15行遇到了困难。编译器无法访问我的类型后面的数组,并且不想通过索引来访问数组的值。我如何实现替换数组的给定部分?
谢谢!
英文:
I am trying to add or replace (or add) a field in a custom type that is nothing but an array of structs based on a struct field. Basically something simple, have a look here:
https://play.golang.org/p/Fb04g4Oq1C
Line 15 is where I am struggling. The compiler does not get to the array behind my type and does not want to address the array values by there index. How can I achieve that the given part of the array will be replaced?
Thanks!
答案1
得分: 3
将
*v[i] = n
替换为
(*v)[i] = n
前者表示“取v[i]
指向的内容”,而后者表示“取v
指向的内容,并取第i
个元素”。
英文:
Replace
*v[i] = n
with
(*v)[i] = n
The former means "take what v[i]
points to", while the latter, "take what v
points to and take i
'th element".
答案2
得分: 1
如此答案中所提到的,切片本身已经是一种指针,因此将切片的指针作为参数传递是完全没有必要的。
这意味着你可以使用[]
而不是[]
的指针版本,代码仍然可以正常工作。参考这个示例:
func (v VarBucket) AddOrReplace(n Var) VarBucket {
for i, vars := range v {
if vars.Name == n.Name {
v[i] = n
fmt.Println("Replaced")
return v
}
}
v = append(v, n)
fmt.Println("Added")
return v
}
v_a := Var{Name: "a", Value: "A"}
v_b := Var{Name: "b", Value: "B"}
v_c := Var{Name: "a", Value: "C"}
b := VarBucket{}
b = b.AddOrReplace(v_a) // 添加
fmt.Printf("%v\n", b)
b = b.AddOrReplace(v_b) // 添加
fmt.Printf("%v\n", b)
b = b.AddOrReplace(v_c) // 替换 v_a
fmt.Printf("%v\n", b)
输出结果:
Added
[{a A}]
Added
[{a A} {b B}]
Replaced
[{a C} {b B}]
英文:
As mentioned in this answer, a slice is already a kind of pointer, rendering a pointer to a slice totally useless.
That means a version of your code using []
instead of a pointer to []
works just fine.
See this example:
func (v VarBucket) AddOrReplace(n Var) VarBucket {
for i, vars := range v {
if vars.Name == n.Name {
v[i] = n
fmt.Println("Replaced")
return v
}
}
v = append(v, n)
fmt.Println("Added")
return v
}
With:
v_a := Var{Name: "a", Value: "A"}
v_b := Var{Name: "b", Value: "B"}
v_c := Var{Name: "a", Value: "C"}
b := VarBucket{}
b = b.AddOrReplace(v_a) // add
fmt.Printf("%v\n", b)
b = b.AddOrReplace(v_b) // add
fmt.Printf("%v\n", b)
b = b.AddOrReplace(v_c) // replace v_a
fmt.Printf("%v\n", b)
Output:
Added
[{a A}]
Added
[{a A} {b B}]
Replaced
[{a C} {b B}]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论