aghast
aghast

Reputation: 15300

Can I use a "displaced" array base in 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?

Upvotes: 0

Views: 55

Answers (1)

user2357112
user2357112

Reputation: 280291

displaced := array[offset:]

Just slice it.

Demo.

Upvotes: 4

Related Questions