Golang更新作为接口传递的函数内的结构字段

Ark*_*Roy 1 reflection struct interface embedding 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)
}

Run Code Online (Sandbox Code Playgroud)

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

在这种情况下,领域FruitAnimal是一样的:label。但它不会总是如此。请在提供建议时牢记这一点。

任何指导将不胜感激。

col*_*tor 5

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

这应该让你去:

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()
}
Run Code Online (Sandbox Code Playgroud)

游乐场:https : //play.golang.org/p/27yDVLr-zqd