dongpiao1983 2019-01-11 11:09
浏览 13
已采纳

从结构中删除元素,但仅用于此功能

So I have an Struct that holds data that has a AddedByUser which links to my User Struct.

What I want to be able to do it remove the UserLevel from the AddedByUser

Now I want to be able to do it from this function only, so using the json:"-" is not an option. That would remove it from all json output. I only want to remove it form this one function.

I should also say that these are Gorm models and when I have been trying to remove the 10 option (UserLevels) it only removes the outer data set not the UserLevel from all of the data.

{
    "ID": 1,
    "CreatedAt": "2019-01-08T16:33:09.514711Z",
    "UpdatedAt": "2019-01-08T16:33:09.514711Z",
    "DeletedAt": null,
    "UUID": "00000000-0000-0000-0000-000000000000",
    "Title": "title000",
    "Information": "info999",
    "EventDate": "2006-01-02T15:04:05Z",
    "AddedByUser": {
        "ID": 2,
        "CreatedAt": "2019-01-08T15:27:52.435397Z",
        "UpdatedAt": "2019-01-08T15:27:52.435397Z",
        "DeletedAt": null,
        "UUID": "b019df80-a7e4-4397-814a-795e7e84b4ca",
        "Firstname": "Me",
        "Surname": "admin",
        "Password": "....",
        "Email": "admin@email.co.uk",
        "UserLevel": {
            "ID": 0,
            "CreatedAt": "0001-01-01T00:00:00Z",
            "UpdatedAt": "0001-01-01T00:00:00Z",
            "DeletedAt": null,
            "LevelTitle": "",
            "UserLevel": null
        },

So this is what I have tried,

data := []models.MyData{}
data = append(data[0:2])

I have about 14 results, with out the append it loads all the results but with this is only loads two results. The idea was to remove either UpdateAt or Title. As I am not sure if the gorm model information is all 0 or if the slice sees them as 0,1,2,3,4 etc.

I have also tried to range over the slice of models, while I can access each of the sections, I can not seem to find a simple method to remove data by name from a struct? Maps seem to have that but not structs which I am not sure why?

Thanks.

UPDATE

This is the model I am using:

//Model
type MyData struct {
  gorm.Model
  UUID              uuid.UUID
  Title       string
  Information string
  EventDate       time.Time

  AddedByUser   Users `gorm:"ForeignKey:added_by_user_fk"`
  AddedByUserFK uint
 }

//Users Model
type Users struct {
  gorm.Model
  UUID      uuid.UUID
  Firstname string
  Surname   string
  Password  string
  Email     string

  UserLevel   UserLevels `gorm:"ForeignKey:user_level_fk" json:",omitempty"`
  UserLevelFK uint
}
  • 写回答

1条回答 默认 最新

  • doudao7511 2019-01-11 11:42
    关注

    As mentioned in the comments, you cannot remove fields from a struct value, because that would yield a value of a different type.

    However, you can set fields to their zero value. Combined with the omitempty JSON tag, you can exclude fields from the JSON encoding. To make this work properly, you have to change the UserLevel field to a pointer type (otherwise you end up with empty objects in the JSON document).

    Types shortened for brevity:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type MyData struct {
        Title       string
        AddedByUser Users
    }
    
    type Users struct {
        ID        int
        UserLevel *UserLevels `json:",omitempty"` // pointer type with omitempty
    }
    
    type UserLevels struct {
        LevelTitle string
    }
    
    func main() {
        var x MyData
        x.Title = "foo"
        x.AddedByUser.ID = 2
        x.AddedByUser.UserLevel = &UserLevels{}
    
        f(x)
    
        b, _ := json.MarshalIndent(x, "", "  ")
        fmt.Println("main:
    " + string(b))
    }
    
    func f(x MyData) {
        // "unset" UserLevel. Since we are receiving a copy of MyData, this is
        // invisible to the caller.
        x.AddedByUser.UserLevel = nil
    
        b, _ := json.MarshalIndent(x, "", "  ")
        fmt.Println("f:
    " + string(b))
    }
    
    // Output:
    // f:
    // {
    //   "Title": "foo",
    //   "AddedByUser": {
    //     "ID": 2
    //   }
    // }
    // main:
    // {
    //   "Title": "foo",
    //   "AddedByUser": {
    //     "ID": 2,
    //     "UserLevel": {
    //       "LevelTitle": ""
    //     }
    //   }
    // }
    

    Try it on the playground: https://play.golang.org/p/trUgnYamVOA

    Alternatively, you can define new types that exclude the AddedByUser field. However, since this field isn't at the top level, this is a lot of work, and it's easy to forget to update those types when new fields are added to the original types.

    If the field were at the top level, the compiler would do most of the work for you, because types that only differ in their field tags can be directly converted to one another:

    type MyData struct {
        ID    int
        Title string
    }
    
    func main() {
        var x MyData
        x.ID = 1
        x.Title = "foo"
    
        f(x)
    }
    
    func f(x MyData) {
        type data struct { // same as MyData, except the field tags
            ID    int
            Title string `json:"-"`
        }
    
        b, _ := json.MarshalIndent(data(x), "", "  ")
        fmt.Println("main:
    " + string(b))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值