我正在使用 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
uj5u.com熱心網友回復:
你放了一個型別約束:
type TModel interface {
MyUser | AnotherModel
...
在您的界面中,因此您不能使用 a*MyUser作為型別引數TModel
修復編譯時錯誤:更改型別約束
type TModel interface {
*MyUser | *AnotherModel
...
}
https://go.dev/play/p/1oP2LzeqXIa
多說一句:除非你別有用心地明確列出唯一可以用作 a 的型別,否則TModel我會說
type TModel interface {
SetName(s string)
}
對于您的泛型型別來說,這可能是一個足夠的約束。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/494526.html
