我正在开发一个程序,需要使用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;
}
答案 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"};
个人意见时间,使用反射而不是使用简单的界面是:
使用界面的示例:
{{1}}
答案 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)
}