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

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

如何避免對具有不同功能的相同模式進行 go lint 重復(fù)?

如何避免對具有不同功能的相同模式進行 go lint 重復(fù)?

Go
30秒到達戰(zhàn)場 2022-11-23 20:03:25
我在重構(gòu)代碼時遇到困難,因為 lint 檢測到模式重復(fù)但功能不同。代碼是這樣的,它是為帶有 protobuf 定義的 grpc 實現(xiàn)的func (svc *UserService) CreateUser(ctx context.Context, req *pb.CreateUserRequest) (*pb.CreateUserResponse, error) {    err := svc.validateCreateUser(req)    if err != nil {        return nil, err    }    user, err := svc.repo.CreateUser(ctx, req)    if err != nil {        return nil, err    }    return user, nil}func (svc *UserService) UpdateUser(ctx context.Context, req *pb.UpdateUserRequest) (*pb.UpdateUserResponse, error) {    err := svc.validateUpdateUser(req)    if err != nil {        return nil, err    }    user, err := svc.repo.UpdateUser(ctx, req)    if err != nil {        return nil, err    }    return user, nil}提前致謝。我不知道如何避免重復(fù),因為函數(shù)也有不同的參數(shù)類型。
查看完整描述

1 回答

?
慕碼人8056858

TA貢獻1803條經(jīng)驗 獲得超6個贊

并非所有 lint 問題都必須修復(fù)


如果您認為它會犧牲可讀性,請?zhí)砑?// nolint


但是……您可以使用泛型重構(gòu)它們的代碼



func [T, V any] someNameToBeDefined(

    ctx context.Context,

    target T,

    validator func(T) error,

    executor func(context.Context, T) (V, error),

    ) (V, error){

    if err := validator(target); err!= nil { … }

    return executor(ctx, target)

}


func (svc *UserService) CreateUser(

   ctx context.Context, 

   req *pb.CreateUserRequest,

) (*pb.CreateUserResponse, error) {

  return someNameToBeDefined(ctx,

     req,

     svc.validateCreateUser,

     svc.repo.CreateUser,

    )

}


如果您認為這是可讀的,請繼續(xù)。


但也許這可能不是正確的方法。


例如,您的存儲庫可以在創(chuàng)建/更新之前驗證請求。


這是一種比使用泛型和函數(shù)指針恕我直言更具可讀性的方法


查看完整回答
反對 回復(fù) 2022-11-23
  • 1 回答
  • 0 關(guān)注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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