我正在玩 golang 泛型,試圖對所有 mongo 集合實施 CRUD 操作,但我在嘗試直接更新結(jié)構(gòu)上的某些字段時遇到問題,但出現(xiàn)錯誤package mainimport ( "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 structfunc (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 沒有實現(xiàn) TModel(SetName 方法有指針接收器)我嘗試從更改func(s *MyUser)為func (s MyUser)但是結(jié)構(gòu)沒有反映更改ineffective assignment to field MyUser.Name (staticcheck)游樂場:https ://go.dev/play/p/GqKmu_JfVtC
1 回答

泛舟湖上清波郎朗
TA貢獻1818條經(jīng)驗 獲得超3個贊
你放了一個類型約束:
type TModel interface {
MyUser | AnotherModel
...
在您的界面中,因此您不能將 a*MyUser用作類型參數(shù)TModel
要修復編譯時錯誤:更改類型約束
type TModel interface {
*MyUser | *AnotherModel
...
}
https://go.dev/play/p/1oP2LzeqXIa
一個額外的評論:除非你別有用心地明確列出唯一可以用作 a 的類型,否則TModel我會說
type TModel interface {
SetName(s string)
}
對你的泛型類型來說可能已經(jīng)足夠了。
- 1 回答
- 0 關注
- 134 瀏覽
添加回答
舉報
0/150
提交
取消