duadlkc5762218 2016-06-01 00:44
浏览 107
已采纳

golang-解引用后从struct获取接口实现实例

Create a struct that implements an interface. Encapsulate it into another struct. Fetch the struct / dereference it.

  1. Fetching gets pointer to the implementation of the interface.
  2. Dereferencing the pointer results in another point to the interface.

Why wouldn't dereferencing the pointer to the implementation gives the implementation instance?

package main

import (
    "fmt"
    "net/http"

    "golang.org/x/net/http2"
)

func main() {
    transport := &http2.Transport{}
    client := &http.Client{Transport: transport}

    tmp1 := client.Transport
    tmp2 := &client.Transport
    tmp3 := &tmp1

    fmt.Printf("%T
%T
%T
", tmp1, tmp2, tmp3)

    //dialTLS := tmp1.DialTLS
}

This code outputs...

*http2.Transport
*http.RoundTripper
*http.RoundTripper

As well, trying to access a property of the tmp1 (uncommenting dialTLS := tmp1.DialTLS) results in compile error...

tmp1.DialTLS undefined (type http.RoundTripper has no field or method DialTLS)

...even though fmt.Printf("%+v", tmp1) outputs...

&{DialTLS:<nil> TLSClientConfig:0xc8203ec8c0 ConnPool:<nil> DisableCompression:false MaxHeaderListSize:0 t1:<nil> connPoolOnce:{m:{state:0 sema:0} done:0} connPoolOrDef:<nil>}

What I am attempting to do is access DialTLS in the Transport instance.

  • 写回答

1条回答 默认 最新

  • drzip28288 2016-06-01 01:02
    关注

    You have a type mismatch here. If you look at the documentation, you'll see that the field Transport of the Client struct returns an interface RoundTripper:

    type Client struct {
        // Transport specifies the mechanism by which individual
        // HTTP requests are made.
        // If nil, DefaultTransport is used.
        Transport RoundTripper
    
        // ...
    }
    

    So, the type of tmp1 is http.RoundTripper, though the underlying type is *http2.Transport which implements the RoundTripper interface.

    As for tmp2 and tmp3, they are seen as pointers to a RoundTripper and not as **http2.Transport.

    In order to retrieve the DialTLS field, you have to use type assertions to convert a RoundTripper back into a Transport:

    dialTLS := client.Transport.(*http2.Transport).DialTLS
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)