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 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教