2

Don't ask me why I'm doing this, just tell me how it's possible:

gopls error: mismatched types string and string

type Mapsi2[T string | int | float32 | float64] struct {
    Keys   []string
    Values []T
}

func (mapsi Mapsi2[string]) SetValue(key string, value string) {
    for i, keyMapsi := range mapsi.Keys {
        if key == keyMapsi {
            mapsi.Values[i] = value
        }
    }
}

At first I thought that the lsp server was stupid, but it turns out that it is not.

go error: mismatched types string and string

go run ./cmd/app
# devllart/foobarman/src/mapsi
src/mapsi/mapsi.go:48:13: invalid operation: key == keyMapsi (mismatched types string and string)
make: *** [Makefile:6: run] Error 2

I googled and in the search results there are only errors with compare the pointer with a string... Right there with the types everything is normal or I'm mistaken.

Ruslan
  • 31
  • 5

1 Answers1

1

Your method signature should be func (mapsi Mapsi2[T]) SetValue(key string, value T).

Unrelated to your compilation issue, but note:

  • you probably want to use a pointer receiver so the changes persist outside the method call
  • you also might want to handle the case where the key isn't found

View it on the playground: https://go.dev/play/p/YBcVn_EKXQe.

Gavin
  • 4,365
  • 1
  • 18
  • 27
  • Thank you, this is I needed. In fact, I just somehow missed the fact that multiple types for structure methods can using in this way. – Ruslan Jan 30 '23 at 19:59
  • PS: And I was going to process an unfound key, but I didn’t know about the pointer receiver — I’ll take note. – Ruslan Jan 30 '23 at 20:10