Replace methode for a custom type array in golang

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

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}]

huangapple
  • 本文由 发表于 2014年11月24日 19:41:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/27103992.html
匿名

发表评论

匿名网友

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

确定