Home > Software design >  Maybe bag in golang (mismatched types string and string)
Maybe bag in golang (mismatched types string and string)

Time:01-31

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.

CodePudding user response:

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.

  • Related