小编Ark*_*Roy的帖子

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

我是新手(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函数,以便它将当前时间放入 …

reflection struct interface embedding go

1
推荐指数
1
解决办法
2099
查看次数

标签 统计

embedding ×1

go ×1

interface ×1

reflection ×1

struct ×1