英文:
Maybe bag in golang (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 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
我搜索了一下,搜索结果中只有与将指针与字符串进行比较的错误... 在这里,类型都是正常的,或者我弄错了。
英文:
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.
答案1
得分: 1
你的方法签名应该是 func (mapsi Mapsi2[T]) SetValue(key string, value T)
。
与你的编译问题无关,但请注意:
- 你可能想要使用指针接收器,以便更改在方法调用之外仍然存在
- 你可能还想处理找不到键的情况
在 playground 上查看:https://go.dev/play/p/YBcVn_EKXQe。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论