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
Release: 2024-12-13 13:45:11
Original
489 people have browsed it

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)
}
Copy after login

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
}
Copy after login

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

cannot infer V
Copy after login

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")
Copy after login

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")
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template