可以从现有的引用创建一个切片吗?

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

Is it possible to create a slice from an existing reference?

问题

假设我有以下函数:

func foo(bar []int) {
    bar[0] = 456
}

我想创建一个引用a[]int,这样当我执行以下操作时:

var a int = 10
// mySlice := ... crazy hackery?
foo(mySlice)

a的值将变为456。


我知道这很疯狂、愚蠢,而且根本不是正确的做法。我不是在寻找“正确”的方法。foo函数的原型必须保持不变。

我可以保证,尽管底层的int会改变,但指向它的切片是不可变的。

之所以有这个奇怪的要求,是因为这是为了c2go项目

英文:

Let's say I have the following function:

func foo(bar []int) {
    bar[0] = 456
}

I want to create an []int with one element that references a, such that when I:

var a int = 10
// mySlice := ... crazy hackery?
foo(mySlice)

The value of a will be 456.


I know this is crazy and stupid and not at all the right thing to do. I'm not looking for the "correct" way. The function prototype for foo must remain the same.

I can guarantee that while the underlying int will change, the slice that points to it is immutable.

The reason for the strange requirement is because this is for the c2go project.

答案1

得分: 0

你可以通过unsafe.Pointer将任何类型转换为你想要的类型。

首先将*int转换为指向数组的指针,然后对其进行切片:

(*[1]int)(unsafe.Pointer(&a))[:]

https://play.golang.org/p/bmKcMIj3pb

英文:

You can cast any types you want through an unsafe.Pointer.

First convert the *int to a pointer to an array, then slice it:

(*[1]int)(unsafe.Pointer(&a))[:]

https://play.golang.org/p/bmKcMIj3pb

huangapple
  • 本文由 发表于 2017年5月21日 22:21:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/44097977.html
匿名

发表评论

匿名网友

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

确定