在 golang 中如何修改传递给结构的空接口的值?
时间:2024-03-11
浏览:489
作者:佚名
知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《在 golang 中如何修改传递给结构的空接口的值?》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!
问题内容
我有许多结构体作为指针传递给一个名为 autofilled 的函数。每个结构都彼此不同。但有些字段是相同的,例如“creator”,“createon”,“edition”.., 有什么方法可以更改自动填充功能中的公共字段吗?
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")
}解决方案
看起来您只需要在其他结构中嵌入一个通用结构(有时称为 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 上的方法。 (使用接口会失去类型安全性。)
func (c *common)autofill() {
// set fields on common struct
}
func main() {
user := &user{}
user.autofill()@ajr 给出了一个非常好的选择。这是另一种方法。
对于每个结构体(book 和 user),创建一个名为 new<structname 的方法。以book为例
func newbook() *book {
return &book {
//you can fill in default values here for common construct
}
}
您可以通过创建 common 结构来进一步扩展此模式,并在创建时将该对象传递给 newbook,即
func newbook(c common) *book {
return &book {
common: c
//other fields here if needed
}
}
现在在您的主代码中,您将执行此操作
func main() {
c := NewCommon() //this method can create common object with default values or can take in values and create common object with those
book := NewBook(c)
//now you don't need autofill method
fmt.Println("Thanks, playground")
}以上就是《在 golang 中如何修改传递给结构的空接口的值?》的详细内容,更多关于的资料请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.28
11.28
11.28
11.28
11.28
11.28
11.28
11.28
热门专题
