How to modify a slice element which is a struct in golang?

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

How to modify a slice element which is a struct in golang?

问题

你有一个包含结构体的 Golang 切片,并且想要修改其中的一个条目。

type Type struct {
    value int
}

func main() {

    s := []Type{{0}, {0}}

    // 打印 [{0} {0}]
    fmt.Println(s)

    firstEntry := s[0]
    firstEntry.value = 5

    // 仍然打印 [{0} {0}]
    fmt.Println(s)
}

使用方括号操作符并修改其返回值并不会改变切片本身。

有什么推荐的方法可以修改切片中的条目?

英文:

You have a golang slice of structs and you would like to change one entry in there.

type Type struct {
	value int
}

func main() {

	s := []Type{{0}, {0}}

	// Prints  [{0} {0}]
	fmt.Println(s)

	firstEntry := s[0]
	firstEntry.value = 5

	// Also prints [{0} {0}]
	fmt.Println(s)
}

https://play.golang.org/p/32tpcc3-OD

Using the brackets operator and modifying its return does not change the slice itself.

What is the recommended way of doing this slice entry modification ?

答案1

得分: 41

尝试一下:

s[0].value = 5

这将访问切片的底层存储。另外,

p := &s[1]
p.value = 6
英文:

Try

s[0].value = 5

This gets to the backing store of the slice. Also

p := &s[1]
p.value = 6

答案2

得分: 6

你也可以直接获取切片元素的地址并对其进行解引用:

func main() {

	s := []Type{{0}, {0}}

	// 打印 [{0} {0}]
	fmt.Println(s)

    // 对切片元素的地址进行解引用
	(&s[0]).value = 5
	
	// 打印 [{5} {0}]
	fmt.Println(s)
}
英文:

You can also take the address of the slice element directly and de-reference it:

func main() {

	s := []Type{{0}, {0}}

	// Prints  [{0} {0}]
	fmt.Println(s)

    // De-reference the address of the slice element
	(&s[0]).value = 5
	
	// Prints [{5} {0}]
	fmt.Println(s)
}

huangapple
  • 本文由 发表于 2016年12月14日 01:42:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/41127380.html
匿名

发表评论

匿名网友

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

确定