将指针用作函数的参数

huangapple go评论105阅读模式
英文:

Use pointer as a function's argument

问题

如何使用函数参数的方法?

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])
}

在这个例子中,我无法使用c变量的参数,或者也许还有其他选项可以将c作为参数传递给函数?

英文:

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?

答案1

得分: 1

writeToInflux函数中,c interface{}没有指定任何c应该实现的方法。你应该使用InfluxWriter接口,这样你就可以调用c.Write方法:

type InfluxWriter interface {
    Write(bp client.BatchPoints) (*client.Response, error)
}

另外,writeToInflux函数可以接受一个client.Client参数,这样你就可以访问它的所有方法。

英文:

In writeToInflux, the c interface{} doesn't specify any methods c should implement. You should use sine InfluxWriter interface so you can call c.Write:

type InfluxWriter {
    Write(bp client.BatchPoints) (*client.Response, error)
}

Alternatively, writeToInflux can accept a client.Client, giving you access to all its methods.

答案2

得分: -1

"c"是一个interface{}类型,在函数参数中使用接口,可以将任何结构体或任何数据类型传递给它。

在你的情况下,你想让c使用write函数
如果 err := c.Write(bp); err != nil {
log.Print("write failed " + err)
}
编译器不知道c的类型,所以你需要进行类型断言。

尝试这样做,它会起作用

newC, ok := c.(c的类型) c的类型 -> 一个结构体或任何具有write方法的类型

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

}
或者像这样更改你的函数

func writeToInflux(c client.Client, host string, service string, state string) bool

英文:

"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

huangapple
  • 本文由 发表于 2017年7月17日 21:41:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/45145873.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定