如何解决 Go 在泛型函数中出现'无法推断类型参数 V”错误?
无法推断类型参数 V
考虑以下 Go 代码:
package cfgStorage type WritableType interface { ~int | ~string | ~float64 } type ConfigStorage[K, V WritableType] interface { get(key K) (V, error) set(key K, value V) (bool, error) } func GetValue[K, V WritableType, C ConfigStorage[K, V]](storage C, key K) (V, error) { res, err := storage.get(key) return res, err } func SetValue[K, V WritableType, C ConfigStorage[K, V]](storage C, key K, value V) (bool, error) { res, err := storage.set(key, value) return res, err } type FileSystemStorage[K, V WritableType] struct { } func (f FileSystemStorage[K, V]) get(key K) (V, error) { /// my code to load data from json file } func (f FileSystemStorage[K, V]) set(key K, value V) (bool, error) { /// my code to save data as json file } func main() { var fileStorage cfgStorage.FileSystemStorage[string, string] setResult, _ := cfgStorage.SetValue(fileStorage, "key", "value") if setResult == false { log.Fatal("Error setting value") } var result string result, _ = cfgStorage.GetValue(fileStorage, "key") fmt.Println(result) }
调用 GetValue 函数时, Go 编译器报告错误:
cannot infer V
原因
在 Go 1.20 及更早版本中,类型推断算法无法仅根据提供的参数存储和键来推断 V 的类型。约束类型推断规则允许从已知类型参数推导未知类型参数。然而,在这种情况下,满足 ConfigStorage[K, V] 约束的具体类型是未知的。
解决方案
要解决此问题,需要显式类型参数调用GetValue时必须提供:
result, _ = GetValue[string, string](fileStorage, "key")
Go 1.21
在 Go 1.21 中,类型推断算法已得到增强,可以在将值分配给接口时考虑方法。这意味着现在可以从匹配方法的相应参数类型推断出方法签名中使用的类型参数。因此,在 Go 1.21 及更高版本中,您可以简单地调用:
result, _ = GetValue(fileStorage, "key")
而无需显式指定类型参数。
以上是如何解决 Go 在泛型函数中出现'无法推断类型参数 V”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Golang在性能和可扩展性方面优于Python。1)Golang的编译型特性和高效并发模型使其在高并发场景下表现出色。2)Python作为解释型语言,执行速度较慢,但通过工具如Cython可优化性能。

Golang在并发性上优于C ,而C 在原始速度上优于Golang。1)Golang通过goroutine和channel实现高效并发,适合处理大量并发任务。2)C 通过编译器优化和标准库,提供接近硬件的高性能,适合需要极致优化的应用。

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

Golang适合快速开发和并发场景,C 适用于需要极致性能和低级控制的场景。1)Golang通过垃圾回收和并发机制提升性能,适合高并发Web服务开发。2)C 通过手动内存管理和编译器优化达到极致性能,适用于嵌入式系统开发。

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。 Golang以其并发模型和高效性能着称,Python则以简洁语法和丰富库生态系统着称。

Golang和C 在性能上的差异主要体现在内存管理、编译优化和运行时效率等方面。1)Golang的垃圾回收机制方便但可能影响性能,2)C 的手动内存管理和编译器优化在递归计算中表现更为高效。

Golang和C 在性能竞赛中的表现各有优势:1)Golang适合高并发和快速开发,2)C 提供更高性能和细粒度控制。选择应基于项目需求和团队技术栈。

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t
