第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在其他泛型類型中使用 setter 方法的約束

在其他泛型類型中使用 setter 方法的約束

Go
蠱毒傳說 2022-12-19 21:34:32
我正在玩 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)足夠了。


查看完整回答
反對 回復 2022-12-19
  • 1 回答
  • 0 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號