Home  >  Article  >  Backend Development  >  Maybe it's bag in golang (type string and string don't match)

Maybe it's bag in golang (type string and string don't match)

WBOY
WBOYforward
2024-02-09 08:06:18400browse

也许是 golang 中的 bag(类型字符串和字符串不匹配)

php editor Xinyi introduces to you the bag types in golang. In golang, the bag type refers to a data structure used to store a collection of elements. Unlike other data structures, elements in a bag can appear repeatedly and the order does not matter. This means that the bag type is very useful in situations where order is not required, such as calculating the frequency of elements or determining whether an element exists. It should be noted that the bag type and string type do not match in golang, so you need to pay attention to type conversion issues during use.

Question content

Don’t ask me why I do this, just tell me how it is possible:

gopls error: string and string type mismatch

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 the lsp server was stupid, but it turned out not to be the case.

Error occurred: string and string type mismatch

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 I get an error only when comparing pointers to strings... right there, the type everything is fine, or I'm wrong.

Workaround

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

has nothing to do with your compilation issue, but please note:

  • You may want to use a pointer receiver so that changes persist beyond method calls
  • You may also want to handle the case where the key is not found

View on the playground: https://www.php.cn/link/6934456f54af5ab56c6f347c6427afeb一个>.

The above is the detailed content of Maybe it's bag in golang (type string and string don't match). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete