gpt4 book ai didi

pointers - 如何更改在golang中作为结构引用传递的空接口(interface)的值?

转载 作者:行者123 更新时间:2023-12-01 22:38:28 24 4
gpt4 key购买 nike

我有许多结构作为指针传递给名为 AutoFilled 的函数。每个结构都不同。但有些字段是相同的,例如“creator”、“createon”、“edition”..,
有什么方法可以更改 AutoFilled 函数中的公共(public)字段?

package main

import (
"fmt"
"time"
)

type User struct {
ID string
Creator string
CreateOn time.Time
Edition int
Name string
Password string
}

type Book struct {
ID string
Creator string
CreateOn time.Time
Edition int
Name string
ISBN string

}

func AutoFilled(v interface{}) {
// Add Creator
// Add CreateOn
// Add Edition (Version) [new is zero, edit increase 1]
}

func main() {
user := User{}
book := Book{}

AutoFilled(&user)
AutoFilled(&book)

fmt.Println(user)
fmt.Println(book)

fmt.Println("Thanks, playground")
}

最佳答案

看起来您只需要在其他结构中嵌入一个 Common 结构(有时称为 mixin)。

type Common struct {
ID string
Creator string
CreateOn time.Time
Edition int
}
type User struct {
Common
Name string
Password string
}

type Book struct {
Common
Name string
ISBN string
}

我也会制作 AutoFilled在 Common 上运行一个方法。 (使用接口(interface)会失去类型安全性。)
func (c *Common)Autofill() {
// set fields on Common struct
}

func main() {
user := &User{}
user.Autofill()

关于pointers - 如何更改在golang中作为结构引用传递的空接口(interface)的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60143465/

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