Pointers in Go

Asked

Viewed 68 times

0

I’m trying to change a String in Go using pointers, but I get one

invalid operation: oculta[i] (type *string does not support indexing)

The function I’m performing the change.

func verifica(palavra, chute string, oculta *string) {
    for i, l := range palavra {
        if string(l) == chute {
            *oculta[i] = chute
        } 
    }
}

1 answer

0


about string: go strings are imutaveis, that is taking specific methods for the string type it n can be modified, unless something is assigned to it altogether

pointers: to avoid ambiguities the way to access a pointer with the use of indices is (*ptr)[i]

by which I understood the code, you want to assign the letter of the kick in the occult, as you cannot manipulate the input of the string directly to assign (to access in a print for example, can), that aq would be a solution to what I believe is the purpose of this function

func verifica(palavra, chute string, nome *string) {
    for _, l := range palavra {
        if string(l) == chute {
            *nome = *nome + chute
        } else {
            *nome = *nome + "_"
        }
    }
}

to use indices the solution I think would be to use Slice byte(byte is kind of golang char)

func verifica(palavra, chute string, nome []byte) {
    for i, l := range palavra {
        if string(l) == chute {
            nome[i] = byte(chute[0])
        } else {
            nome[i] = byte("_"[0])
        }
    }
}

Slice is a pointer, so n needs to receive with *and nor command with &, the only thing is that before sending it he has to create it the size he will use, before this function is called

nome := make([]byte, len(palavra))

of to use Slice with append tb

  • 4

    Just to complement, byte is unsuitable for storing characters, as it has only 8 bits of accuracy, which is not enough to store Unicod characters that require 32 bits, such as emojis or Kanji for example. Prefer the type rune for such cases.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.