doukang2003 2016-05-29 12:21
浏览 27
已采纳

反射-恢复time.Time实例

I am developing a program in go that needs to store and retrieve an array of custom structure instances using the sessions package of the Gorilla toolkit. For restoring the custom structure I need to make use of reflection features. The issue is that my structure named Timestamp includes two time.Time instances and I have not been able to restore the instances. Thus, my question is how to restore a time.Time instance.

Below you can see my code for the Timespan structure as well as the code for storing and reading the Timespan array in the session store.

type Timespan struct {
    ID uint8;
    StartDate time.Time;
    EndDate time.Time;
}

func (server *WebServer) setTimespans(writer http.ResponseWriter, request *http.Request, timespans [model.TimespanCount]*model.Timespan) error {
    var session *sessions.Session;
    var sessionDecodingException error;
    session, sessionDecodingException = server.SessionStore.Get(request, authenticationSessionName);
    if sessionDecodingException != nil {
        return sessionDecodingException;
    }


    session.Values[sessionTimestamps] = timespans;
    return nil;
}

func (server *WebServer) getTimespans(request *http.Request) ([model.TimespanCount]*model.Timespan, error) {
    var session *sessions.Session;
    var sessionDecodingException error;
    session, sessionDecodingException = server.SessionStore.Get(request, authenticationSessionName);
    var readTimespans [model.TimespanCount]*model.Timespan;
    if sessionDecodingException != nil {
        return readTimespans, sessionDecodingException;
    }

    interfaceValue := reflect.ValueOf(session.Values[sessionTimestamps]);
    var actuallyAddedTimespan *model.Timespan;
    for counter := 0; counter < model.TimespanCount; counter++ {
        actuallyAddedTimespan = &model.Timespan{};
        actuallyReflectedTimespan := interfaceValue.Index(counter).Elem();
        actuallyAddedTimespan.ID = uint8(actuallyReflectedTimespan.FieldByName("ID").Uint());
        //actuallyAddedTimespan.StartDate = actuallyReflectedTimespan.FieldByName("StartDate");
        //actuallyAddedTimespan.EndDate = actuallyReflectedTimespan.FieldByName("EndDate");
        fmt.Println(actuallyAddedTimespan);
    }
    return readTimespans, nil;
}
  • 写回答

2条回答 默认 最新

  • dongteng2534 2016-05-29 14:43
    关注

    You need to get the interface to the field:

    actuallyAddedTimespan.StartDate = actuallyReflectedTimespan.FieldByName("StartDate").Interface().(time.Time)
    

    <kbd>playground</kbd>

    Personal opinion time, using reflection for this rather than using a simple interface is:

    1. Slow.
    2. Inefficient
    3. Can break easily if you change how your struct looks and forget to update the reflection code.

    Example of using an interface:

    func main() {
        ts := &Timespan{ID: 102, StartDate: time.Now().AddDate(6, 0, 0), EndDate: time.Now().AddDate(8, 0, 0)}
        m := map[string]interface{}{
            "key": ts,
        }
        switch v := m["key"].(type) {
        case Timespaner:
            fmt.Println(v.Value())
        default:
            fmt.Println("wtfmate?")
        }
    }
    
    func (ts *Timespan) Value() (id uint8, start, end time.Time) {
        return ts.ID, ts.StartDate, ts.EndDate
    }
    
    type Timespaner interface {
        Value() (id uint8, start, end time.Time)
    }
    

    <kbd>playground</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图