gpt4 book ai didi

反射——恢复时间.时间实例

转载 作者:IT王子 更新时间:2023-10-29 01:58:48 25 4
gpt4 key购买 nike

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

下面您可以看到我的Timespan 结构代码,以及在 session 存储中存储和读取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;
}

最佳答案

您需要获取该字段的接口(interface):

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

playground

个人意见时间,为此使用反射而不是使用简单的接口(interface)是:

  1. 慢。
  2. 效率低下
  3. 如果您更改结构的外观并忘记更新反射代码,则很容易崩溃。

使用接口(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)
}

playground

关于反射——恢复时间.时间实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37509845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com