反射 - 恢复time.Time实例

时间:2016-05-29 12:21:08

标签: reflection go

我正在开发一个程序,需要使用Gorilla工具包的sessions包来存储和检索一组自定义结构实例。要恢复自定义结构,我需要使用反射功能。问题是我的名为Timestamp的结构包含两个time.Time个实例,而我无法恢复实例。因此,我的问题是如何恢复time.Time实例。

下面您可以看到我的Timespan结构代码以及在会话存储中存储和读取Timespan数组的代码。

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 个答案:

答案 0 :(得分:2)

您需要获取该字段的界面:

char *my_array[20]={"RED","BLUE","WHITE","BLUE","YELLOW","BLUE","RED","YELLOW","WHITE","BLUE","BLACK","BLACK","WHITE","RED","YELLOW","BLACK","WHITE","BLUE","RED","YELLOW"};

playground

个人意见时间,使用反射而不是使用简单的界面是:

  1. 慢。
  2. 低效
  3. 如果您更改结构的外观并且忘记更新反射代码,则可以轻松破解。
  4. 使用界面的示例:

    {{1}}

    playground

答案 1 :(得分:1)

您可以使用Interface()函数从结构中获取interface{}值。然后,您可以使用类型断言来获取正确的类型:

func main() {
    t := &Timespan{42, time.Now(), time.Now()}
    reflectedPointer := reflect.ValueOf(t)
    reflectedTimespan := reflectedPointer.Elem()
    var timespan Timespan = reflectedTimespan.Interface().(Timespan)
    fmt.Println(*t)
    fmt.Println(timespan)
}