gpt4 book ai didi

go - 更新作为接口(interface)传递的函数内部的结构字段

转载 作者:行者123 更新时间:2023-12-02 23:00:14 25 4
gpt4 key购买 nike

我是 Go (golang) 新手。这就是为什么我的问题可能无关紧要(或无法回答)。

我创建了两个结构。这两个都嵌入了另一个结构。现在我想更新函数内嵌入结构的字段。

package main

import (
"fmt"
"reflect"
"time"
)

type Model struct {
UpdatedAt time.Time
}

type Fruit struct {
Model
label string
}

type Animal struct {
Model
label string
}

func update(v interface{}) {
reflectType := reflect.TypeOf(v)
reflectKind := reflectType.Kind()
if reflectKind == reflect.Ptr {
reflectType = reflectType.Elem()
}
m := reflect.Zero(reflectType)
fmt.Println(m)
}

func main() {
apple := &Fruit{
label: "Apple",
}
tiger := &Animal{
label: "Tiger",
}
update(apple)
update(tiger)
fmt.Println(apple)
fmt.Println(tiger)
}

我希望实现 update 函数,以便它将当前时间放入传递的结构的 UpdatedAt 中。我无法做到这一点。

在这种情况下,FruitAnimal 的字段是相同的:label,但并不总是如此。请在提供建议时牢记这一点。

任何指导将不胜感激。

最佳答案

如果您开始学习 Go,我会避免使用 reflectinterface{}。初学者通常会像 void * 拐杖一样依靠它们。尝试使用具体类型或定义良好的接口(interface)。

这应该能让你继续:

type Timestamper interface {
Update()
UpdatedTime() time.Time
}

type Model struct {
updated time.Time
}

func (m *Model) Update() { m.updated = time.Now() }
func (m *Model) UpdatedTime() time.Time { return m.updated }

type Fruit struct {
Model
label string
}

type Animal struct {
Model
label string
}

// update will work with a `Model` `Animal` or `Fruit`
// as they all implement the `Timestamper` interface`
func update(v Timestamper) {
v.Update()
}

Playground :https://play.golang.org/p/27yDVLr-zqd

关于go - 更新作为接口(interface)传递的函数内部的结构字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58173685/

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