dongzhiyi2006 2018-11-24 10:30
浏览 44
已采纳

如何使用变量访问结构?

I'm new to Go and I'm facing issues in accessing a struct with a variable

I have this function decodeUser. My task is to check whether the keys are present in the request. So this is what I did. I've added a comment where I got the error.

func decodeUser(r *http.Request) (root.User, []string, error) {
    var u root.User
    if r.Body == nil {
        return u, []string{}, errors.New("no request body")
    }
    decoder := json.NewDecoder(r.Body)
    checks := []string{
        "UserName",
        "FirstName",
        "LastName",
        "Email",
    }
    emptyFields := []string{}
    for _, check := range checks {
        // i'm having problem over here `u[check]` it's showing (invalid
           operation: u[check] (type root.User does not support 
           indexing))
        if u[check] == nil {
            emptyFields = append(emptyFields, check)
        }
    }
    err := decoder.Decode(&u)
    return u, emptyFields, err
}

Just in case I added root.User here's structure for it

type User struct {
    ID                   string
    Username             string
    Password             string
    FirstName            string
    LastName             string
    Email                string
    PhoneNumber          string
    PhoneNumberExtension string
    DOB                  time.Time
    AboutMe              string
}

The problem occurs as it doesn't allow me to access struct by a variable and I can't use this method which is u.check. So basically how should I make u[check] work?

  • 写回答

2条回答 默认 最新

  • dtu11716 2018-11-25 15:32
    关注

    This is what worked for me

    for _, check := range checks {
        temp := reflect.Indirect(reflect.ValueOf(&u))
        fieldValue := temp.FieldByName(string(check))
        if (fieldValue.Type().String() == "string" && fieldValue.Len() == 0) || (fieldValue.Type().String() != "string" && fieldValue.IsNil()) {
            fmt.Println("EMPTY->", check)
            emptyFields = append(emptyFields, check)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB怎么通过柱坐标变换画开口是圆形的旋转抛物面?
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿