Home >Backend Development >Golang >How Can I Resolve Go's 'Cannot Infer V' Error When Using Type Constraints in Generic Interfaces?

How Can I Resolve Go's 'Cannot Infer V' Error When Using Type Constraints in Generic Interfaces?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-13 13:45:11426browse

How Can I Resolve Go's

Cannot Infer V: Resolving Infer Type Parameter from Constraint Implementation

The goal is to create an interface in Go that supports saving and loading results in different databases while supporting various data types.

type WritableType interface {
    ~int | ~string | ~float64
}

type ConfigStorage[K, V WritableType] interface {
    get(key K) (V, error)
    set(key K, value V) (bool, error)
}

The problem arises when implementing a file system storage:

type FileSystemStorage[K, V WritableType] struct {
}

func (f FileSystemStorage[K, V]) get(key K) (V, error) {
    // Code to load data from JSON file
}

func (f FileSystemStorage[K, V]) set(key K, value V) (bool, error) {
    // Code to save data as JSON file
}

While calling SetValue, it works successfully. However, when calling GetValue, the compiler encounters an error:

cannot infer V

Solutions

For Go 1.21 and above:

In Go 1.21, type inference has been improved to consider types used in interface methods. Therefore, you can now call GetValue without specifying type parameters:

result, _ = GetValue(fileStorage, "key")

For Go 1.20 and below:

Since the current type inference algorithm doesn't allow inferring V from a constraint implementation, the explicit type parameters must be provided when calling GetValue:

GetValue[string, string](fileStorage, "key")

The above is the detailed content of How Can I Resolve Go's 'Cannot Infer V' Error When Using Type Constraints in Generic Interfaces?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn