也许是在Golang中的包(类型不匹配:字符串和字符串)。

huangapple go评论87阅读模式
英文:

Maybe bag in golang (mismatched types string and string)

问题

不要问我为什么这样做,只告诉我如何可能实现:

gopls错误:类型不匹配 string 和 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错误:类型不匹配 string 和 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

我搜索了一下,搜索结果中只有与将指针与字符串进行比较的错误... 在这里,类型都是正常的,或者我弄错了。

英文:

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.

huangapple
  • 本文由 发表于 2023年1月31日 03:33:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75289266.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定