dourang20110122 2017-07-17 13:41
浏览 45
已采纳

使用指针作为函数的参数

How can I use methods of function arguments?

func writeToInflux(c interface{}, host string, service string, state string) bool {
    fmt.Println(reflect.TypeOf(c), host, service)

    bp, e := client.NewBatchPoints(client.BatchPointsConfig{
        Database:  database,
        Precision: "us",
    })

    if e != nil {
        log.Print(e)
    }

    tags := map[string]string{
        "host":    host,
        "service": service,
    }

    fields := map[string]interface{}{
        "state": state,
    }

    pt, err := client.NewPoint("mon", tags, fields, time.Now())

    if err != nil {
        log.Print(err)
    }

    bp.AddPoint(pt)

    if err := c.Write(bp); err != nil {
        log.Print("write failed " + err)
    }

    return true
}

func handler(w http.ResponseWriter, r *http.Request) {
    c, err := client.NewHTTPClient(client.HTTPConfig{
        Addr:     "http://10.x.x.x:8086",
        Username: username,
        Password: password,
    })
    if err != nil {
        log.Print(err)
    }
    a := strings.Split(r.URL.Path, "/")
    writeToInflux(c, a[3], a[4], a[5])
}

In this example i can't use parameters of c variable, or maybe there is another options to use c as parameter to function?

  • 写回答

2条回答 默认 最新

  • dongshi6529 2017-07-17 13:55
    关注

    "c" is an interface{} type, Having an interface in function parameter, you can able to pass any struct or any data types into it.

    In your case you want c to use the function write
    if err := c.Write(bp); err != nil {
            log.Print("write failed " + err)
        }
    

    The compiler doesn't know the type of c, so you need to type assert it.

    Try this, It will work

    newC,ok:=  c.(type of c)    type of C -> a struct or any type which has a method write
    
    if ok {
        if err := newC.Write(bp); err != nil {
                log.Print("write failed " + err)
            }
    
    }     
    

    Or Change your function like this

    func writeToInflux(c client.Client, host string, service string, state string) bool
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题