无法推断 V:从约束实现推断类型参数

Mar*_*oli 6 generics type-inference constraints go

我有一个界面,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
}

Run Code Online (Sandbox Code Playgroud)

我为此接口实现了文件系统存储,如下所示:

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
}

Run Code Online (Sandbox Code Playgroud)

顺便说一句,当我尝试从中获取实例fileSystem并且SetValue它有效时,但由于GetValue我遇到编译器错误,我的测试代码如下:

var fileStorage cfgStorage.FileSystemStorage[string, string]

setResult, _ := cfgStorage.SetValue(fileStorage, "key", "value")
if setResult == false {
    t.Error()
}
var result string

result, _ = cfgStorage.GetValue(fileStorage, "key")
Run Code Online (Sandbox Code Playgroud)

编译错误位于我调用的行中GetValue

无法推断 V

如果您知道如何解决此问题,请告诉我!

bla*_*een 7

在函数 中GetValue,无法V仅使用提供的参数storage C和来推断 的类型key K

您要求V从实现通用约束的具体类型中进行推断ConfigStorage[K, V]。当前的类型推断算法不支持这一点。Go github存储库中的相关问题是41176: 无法推断通用接口类型,以及5048440018

还有关于类型推断的相关提案部分:

我们可以在函数调用中使用函数参数类型推断,从非类型参数的类型中推断出类型参数。我们可以使用约束类型推断从已知类型参数推导出未知类型参数

所以你可能会说C实际上并不知道,你只知道它实现了约束ConfigStorage[K, V]

您必须GetValue使用显式类型参数进行调用:

// first string for K, second string for V
GetValue[string, string](fileStorage, "key")
Run Code Online (Sandbox Code Playgroud)

固定游乐场:https://gotipplay.golang.org/p/KoYZ3JMEz2N