Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Maybe bag in golang (mismatched types string and string)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading