go - 函数不适用于 if else 语句
问题描述
我正在尝试以 Go 为教程构建一个基本的缓存系统。
由于某种原因,当我运行它时,if else 语句会导致错误。
package datasource
import (
"fmt"
"github.com/patrickmn/go-cache"
"time"
)
type DataSource interface {
Value(key string) (interface{}, error)
}
// DataSourceStr type, implements the DataSource interface
type DataSourceStr struct {
data map[string]string
}
var cache = cache.New(5*time.Minute, 5*time.Minute)
func (n *DataSourceStr) Value(key string) (interface{}, error) {
/*
1. Compute a cache key
2. Search cache key
3. If hit return value
4. If miss, do datasource
5. Cache and return slow thing.
*/
cached, found := cache.Value(key)
if found {
return cached, nil
}
else if _, ok := n.data[key]; ok
{
//measure how often a key gets called.
cache.Set(key, n.data[key], cache.DefaultExpiration)
return n.data[key], nil
} else {
return nil, fmt.Errorf("key not found %v", ok)
}
}
func getFromDS(datasource DataSource, key string) (string, error) {
v, err := datasource.Value(key)
//create a map that decays based on time.
if err != nil {
return "", nil
}
return fmt.Sprint(v), nil
}
我究竟做错了什么?我正在尝试输入一个键,然后从缓存或数据库中返回值。不知道我在语法上做错了什么!
解决方案
推荐阅读
- java - 根据其他类的数据设置自动选中的单选按钮
- zooming - 地图最大程度缩小时允许捏合缩放手势
- c# - 将多个 JSON 文件合并为单个文件
- angularjs - 如何使用angularjs将现有控制器中的值填充/获取到表单字段中
- javascript - 如何使用从 ajax 请求中获得的变量以及其他变量并在函数中使用它们?
- mongodb - 将嵌入属性重写为所有文档的顶级字段
- html - 我想显示具有静态尺寸的图像,与显示器分辨率无关
- c# - 以 STAThread 身份打开新窗口
- laravel - 翻译页面 - 缺少 Route 所需的参数
- razor - .NET Core Razor 页面中的级联下拉菜单(无 MVC/控制器)