使用通用接收器时类型字符串和字符串不匹配[重复]

问题描述 投票:0回答:1

不要问我为什么要这样做,只要告诉我这是怎么可能的:

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
        }
    }
}

一开始我以为lsp服务器很傻,但事实证明并非如此。

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

我用谷歌搜索,在搜索结果中只有将指针与字符串进行比较时出现错误...就在那里,类型一切正常或者我错了。

go generics compiler-errors
1个回答
1
投票

您的方法签名应该是

func (mapsi Mapsi2[T]) SetValue(key string, value T)

与您的编译问题无关,但请注意:

  • 您可能想使用指针接收器,以便更改在方法调用之外持续存在
  • 您可能还想处理找不到钥匙的情况

在操场上查看:https://go.dev/play/p/YBcVn_EKXQe

© www.soinside.com 2019 - 2024. All rights reserved.