登录
首页 >  Golang >  Go问答

使用结构字段的值进行部分更改

来源:stackoverflow

时间:2024-02-05 16:44:11 340浏览 收藏

大家好,今天本人给大家带来文章《使用结构字段的值进行部分更改》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我是 Go 新手,正在尝试创建 CRUD API。请原谅 Go 中的 OOP 方法可能不聪明。我有一个结构,我想通过 PATCH 端点进行部分更新。

type Book struct {
  Id        uuid.UUID  `json:"id"`
  Author    uuid.UUID  `json:"author"`
  Title     string     `json:"title"`
  IsPublic  bool       `json:"isPublic"`
  CreatedAt time.Time  `json:"createdAt"`
  UpdatedAt *time.Time `json:"updatedAt"`
  DeletedAt *time.Time `json:"deletedAt"`
}

我已经定义了第二个结构体,其中包含一本书的可更新属性。

type PatchBookDto struct {
  Author   *uuid.UUID
  Title    *string
  IsPublic *bool
}

在这两个结构中,我都使用(可能滥用?)指针属性来模拟可选参数。我想要实现的是用 PatchBookDto 中的任何给定属性覆盖一本书。这是我迄今为止的尝试:

var book models.Book // Is taken from an array of books
var dto dtos.PatchBookDto

if err := c.BindJSON(&dto); err != nil {
    // Abort
}

dtoTypeInfo := reflect.TypeOf(&dto).Elem()

for i := 0; i < dtoTypeInfo.NumField(); i++ {
    dtoField := dtoTypeInfo.Field(i)
    bookField := reflect.ValueOf(&book).Elem().FieldByName(dtoField.Name)

    if bookField.IsValid() && bookField.CanSet() {

        dtoValue := reflect.ValueOf(dto).Field(i)

        if dtoValue.Interface() == reflect.Zero(dtoValue.Type()).Interface() {
            continue
        }

        if dtoField.Type.Kind() == reflect.Ptr {
            if dtoValue.Elem().Type().AssignableTo(bookField.Type()) {
                bookField.Set(dtoValue.Elem())
            } else {
                // Abort
            }
        }

        convertedValue := dtoValue.Convert(bookField.Type())
        bookField.Set(convertedValue)
    }
}

当我测试这个时,我收到 reflect.Value.Convert: value of type *string Cannot be conversion to type string 错误。

有人知道我可以在这里改进什么以获得我需要的东西吗?


正确答案


看起来您打算将恐慌行放在 if dtoField.Type.Kind() ==reflect.Ptr 的 else 块中。

另一种方法是使用间接指针,然后设置值。

for i := 0; i < dtoTypeInfo.NumField(); i++ {
    dtoField := dtoTypeInfo.Field(i)
    bookField := reflect.ValueOf(&book).Elem().FieldByName(dtoField.Name)
    if bookField.IsValid() && bookField.CanSet() {
        dtoValue := reflect.ValueOf(dto).Field(i)
        if dtoValue.Interface() == reflect.Zero(dtoValue.Type()).Interface() {
            continue
        }
        dtoValue = reflect.Indirect(dtoValue)
        convertedValue := dtoValue.Convert(bookField.Type())
        bookField.Set(convertedValue)
    }
}

以上就是《使用结构字段的值进行部分更改》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>