如何在golang中使用通过引用传递的索引访问切片中的元素

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

How to access elements from slice using index which is passed by reference in golang

问题

我将为您翻译以下内容:

我将一个切片的引用传递给一个函数,并在函数内部对切片进行更改。同时,我尝试使用索引从切片中访问一个元素。在golang中,它会抛出异常。通过引用传递的方式,访问切片中的元素的最佳方法是什么?

您可以在这里找到一个示例代码。[参考:http://www.reddit.com/r/golang/comments/283vpk/help_with_slices_and_passbyreference/ ]。由于我的代码很庞大,我添加了一个示例。

package main

import "fmt"

type mystruct struct {
    val int
}

func main() {
    var s1 []mystruct
    var s2 []mystruct
    
    onlyPassing(&s1)
    s2 = returningToo(s2)
    
    fmt.Printf("%#v\n%#v", s1, s2)
}

func onlyPassing(s *[]mystruct) {
    *s = append(*s, mystruct{1})
    m := (*s)[0]

}

func returningToo(s []mystruct) []mystruct {
    s = append(s, mystruct{1})
    return s
}

您可以在这里找到实现代码1。有人可以帮助我吗?

英文:

I passed a reference of a slice to a function and I am making changes in the slice inside the function. Also I am trying to access an element from the slice using index. It is throwing exception in golang. What is the best way to access an element from a slice by index which is passed by reference?
You can find a sample code here. [ref : http://www.reddit.com/r/golang/comments/283vpk/help_with_slices_and_passbyreference/ ]. Since my code is huge I added a sample.

package main

import "fmt"

type mystruct struct {
	val int
}

func main() {
	var s1 []mystruct
	var s2 []mystruct
	
	onlyPassing(&s1)
	s2 = returningToo(s2)
	
	fmt.Printf("%#v\n%#v", s1, s2)
}

func onlyPassing(s *[]mystruct) {
	*s = append(*s, mystruct{1})
	m := *s[0]

}

func returningToo(s []mystruct) []mystruct {
	s = append(s, mystruct{1})
	return s
}

And you can find the implementation here. Could anyone help me on this.

答案1

得分: 25

索引运算符不会自动解引用指针。你需要使用括号来指定解引用的内容。

m := (*s)[0]
英文:

The index operator doesn't automatically dereference pointers. You need to use parentheses to specify what is dereferenced.

m := (*s)[0]

huangapple
  • 本文由 发表于 2015年2月25日 08:53:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/28709254.html
匿名

发表评论

匿名网友

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

确定