如何使用由golang中的引用传递的索引来访问切片中的元素 [英] How to access elements from slice using index which is passed by reference in golang

查看:256
本文介绍了如何使用由golang中的引用传递的索引来访问切片中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一个切片的引用传递给一个函数,并且我正在对该函数内的切片进行更改。此外,我试图使用索引访问切片中的元素。它在golang中抛出异常。通过引用传递的索引访问切片中元素的最佳方式是什么?
您可以在这里找到示例代码。 [ref: http://www.reddit.com/r/golang/comments / 283vpk / help_with_slices_and_passbyreference / ]。由于我的代码很大,我添加了一个示例。

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
}

你可以找到 here 。有谁能帮我解决这个问题吗?

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

推荐答案

索引操作符不会自动解引用指针。您需要使用圆括号来指定解除引用的内容。

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

m := (*s)[0]

这篇关于如何使用由golang中的引用传递的索引来访问切片中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆