为了账号安全,请及时绑定邮箱和手机立即绑定

迭代时更改值

迭代时更改值

假设我有以下几种类型:type Attribute struct {    Key, Val string}type Node struct {    Attr []Attribute}我想迭代节点的属性以更改它们。我本来希望能够做到:for _, attr := range n.Attr {    if attr.Key == "href" {        attr.Val = "something"    }}但是因为attr不是指针,所以这行不通,我必须这样做:for i, attr := range n.Attr {    if attr.Key == "href" {        n.Attr[i].Val = "something"    }}有没有更简单或更快速的方法?是否可以直接从中获取指针range?显然,我不想仅仅为了迭代而更改结构,更冗长的解决方案不是解决方案。
查看完整描述

3 回答

?
慕运维8079593

TA贡献1876条经验 获得超5个赞

我会采纳您的最后建议,并使用范围的仅索引版本。


for i := range n.Attr {

    if n.Attr[i].Key == "href" {

        n.Attr[i].Val = "something"

    }

}

对我来说,n.Attr[i]在测试Key行和设置行中明确引用似乎更简单Val,而不是attr用于一个和n.Attr[i]另一个。


查看完整回答
反对 回复 2019-12-17
  • 3 回答
  • 0 关注
  • 635 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信