duanbigan7765 2017-07-27 23:48
浏览 18

我可以在Go中使用“位移的”阵列基座吗?

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:

  1. 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]
    
  2. 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
    }
    
  3. 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条回答 默认 最新

  • dtgvl48608 2017-07-27 23:51
    关注
    displaced := array[offset:]
    

    Just slice it.

    Demo.

    评论

报告相同问题?