我正在玩 golang 泛型,试图对所有 mongo 集合实施 CRUD 操作,但我在尝试直接更新结构上的某些字段时遇到问题,但出现错误
package main
import (
"fmt"
)
type TModel interface {
MyUser | AnotherModel
SetName(string)
}
type MyUser struct {
ID string `bson:"_id"`
Name string `bson:"name"`
}
type AnotherModel struct {
ID string `bson:"_id"`
Name string `bson:"name"`
}
// Using this function compiles, but never update the struct
func (s MyUser) SetName(name string) {
s.Name = name
}
/*This should be the right way, but fails at compile time */
/*
func (s *MyUser) SetName(name string) {
s.Name = name
}
*/
type Crud[model TModel] interface {
UpdateObj(m model) (*model, error)
}
type CrudOperations[model TModel] struct {
}
func (c *CrudOperations[model]) UpdateObj(m model) error {
fmt.Printf("\n Obj: %v", m)
m.SetName("NewName")
fmt.Printf("\n Obj: %v", m)
return nil
}
func main() {
c := CrudOperations[MyUser]{}
m := MyUser{Name: "Initial-Name"}
c.UpdateObj(m)
}
./prog.go:44:22: MyUser 没有实现 TModel(SetName 方法有指针接收器)
我尝试从更改func(s *MyUser)为func (s MyUser)但是结构没有反映更改
ineffective assignment to field MyUser.Name (staticcheck)
游乐场:https ://go.dev/play/p/GqKmu_JfVtC
泛舟湖上清波郎朗
相关分类