dongxin8392 2016-06-20 07:49
浏览 49
已采纳

如何在Go中读取嵌入式字段?

I design a new Request structure, but in some scenarios(http.Redirect), I need to get the origin http.Request.

My Request struct:

type Request struct {
    *http.Request
}

func (r *Request) IsGet() bool {
    return strings.EqualFold("GET", r.Method)
}

Main function:

    req := http.Request{
        Method:"POST",
    }

    myReq := &Request{&req}

    // How to get original request.
    originalReq, ok := (interface{}(*myReq)).(http.Request);
    if ok {
        fmt.Printf("Method: %s
", originalReq.Method)
    } else {
        fmt.Println("Failure")
    }
  • 写回答

1条回答 默认 最新

  • douyi7055 2016-06-20 07:56
    关注

    Let's see what the language specification says:

    The unqualified type name acts as the field name.

    // A struct with four anonymous fields of type T1, *T2, P.T3 and *P.T4
    struct {
      T1        // field name is T1
      *T2       // field name is T2
      P.T3      // field name is T3
      *P.T4     // field name is T4
      x, y int  // field names are x and y
    }
    

    i.e. myReq.Request

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM