我有一個界面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
}
順便說一句,當我嘗試從中獲取實體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")
編譯錯誤在我呼叫的行中GetValue:
無法推斷出 V
如果您知道如何解決此問題,請告訴我!
uj5u.com熱心網友回復:
在函式中,僅使用提供的引數和GetValue無法推斷 的型別。Vstorage Ckey K
您要求V從實作泛型約束的具體型別進行推斷ConfigStorage[K, V]。當前的型別推斷演算法不支持這一點。Go github 存盤庫中的相關問題是50484和40018。
還有關于型別推斷的相關提案部分:
我們可以對函式呼叫使用函式引數型別推斷來從非型別引數的型別中推斷出型別引數。我們可以使用約束型別推斷從已知型別引數中推斷出未知型別引數。
因此,您可以爭辯說C實際上并不知道,您只知道它實作了約束ConfigStorage[K, V]。
您必須GetValue使用顯式型別引數呼叫:
// first string for K, second string for V
GetValue[string, string](fileStorage, "key")
固定游樂場:https ://gotipplay.golang.org/p/KoYZ3JMEz2N
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/422100.html
標籤:
上一篇:有雙倍時如何查看方法的接收者
下一篇:編碼base64時的記憶體消耗
