英文:
Can I use a "displaced" array base in Go?
问题
我有一个问题,可以通过使用“偏移数组基址”来很好地解决。也就是说,在C语言中,我会将指针设置为array-base + offset,然后使用ptr[x]
来访问我的数组,这实际上相当于array[offset + x]
,但没有额外的加法运算。
在Go语言中是否可能实现这样的功能?根据我所了解的,我找不到任何支持它的方法(包括一种说法,即Go语言中没有指针算术运算),但是由于切片和其他我目前不熟悉的东西,我想听听更有经验的意见。
编辑
考虑三种可能的情况:
-
我创建了一个数组,并希望将数组的某个“中间索引”作为基址:
sign_values := { -1, -1, -1, -1, -1, 0, 1, 1, 1, 1, 1 } sign := sign + 5 i = f(x) // 返回[-5 .. 5] sign_i = sign[i]
-
我创建了一个数组,并希望将数组的某个“负偏移量”作为基址:
to_lower := { 'a', 'b', 'c', 'd', 'e', ..., 'z' } tolower := to_lower - 'A' func ToLower(ch byte) byte { if isupper(ch) { return tolower[ch] } return ch }
-
我创建了一个数组,并希望将数组的某个“过大的正索引”作为基址。这与其他情况相同,只是期望所有索引都为负数。不知道这在什么情况下会有用。
在所有这些情况下,要求使用负索引(情况1、情况3)或负偏移量(情况2)。据我所知,这至少在某种程度上是不允许的,因为禁止使用负索引。
但也许并非如此?
英文:
I have a problem that would be well solved using a "displaced array base". That is, in C I would set a pointer to array-base + offset, and then access my array using ptr[x]
which would effectively be array[offset + x]
but without the extra addition.
Is such a thing possible in Go? From what I've read, I can't find any support for it (including a statement that there is no pointer arithmetic in Go), but with slices and other things that I'm unfamiliar with so far, I'd like a more experienced opinion.
Edit
Consider three possible scenarios:
-
I create an array, and want to use some "middle index" of the array as the base:
sign_values := { -1, -1, -1, -1, -1, 0, 1, 1, 1, 1, 1 }
sign := sign + 5
i = f(x) // returns [-5 .. 5]
sign_i = sign[i] -
I create an array, and want to use some "negative offset" of the array as the base:
to_lower := { 'a', 'b', 'c', 'd', 'e', ..., 'z' }
tolower := to_lower - 'A'func ToLower(ch byte) byte {
if isupper(ch) {
return tolower[ch]
}return ch
}
-
I create an array and want to use some "excessive positive" index as the base. This would be just the same as the others, except with the expectation that all indices were negative. No idea when this would be useful.
In all of the cases, there is a requirement for either a negative index (case 1, case 3), or for a negative offset (case 2). As far as I can tell, this is disallowed at least somewhat by a prohibition on negative indices.
But maybe not?
答案1
得分: 4
你可以使用切片操作来获取数组中从指定偏移量开始的所有元素。
示例代码请参考这里。
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论