如何在Golang中通过函数传递接口指针?

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

How to pass interface pointer through a function in Golang?

问题

我正在测试golang的功能,并遇到了一个概念,即我可以使用接口的指针作为接口本身。在下面的代码中,我该如何确保one的值变为random

package main

import (
	"fmt"
)

func some(check interface{}) {
	check = "random"
}

func main() {
	var one *interface{}
	some(one)
	fmt.Println(one)
}

具体来说,我需要知道如何将接口指针传递给一个接受接口作为参数的函数。

谢谢!

英文:

I was testing golang functionalities and came across this concept where I can use a pointer of an interface as an interface itself. In the below code, how do I ensure that the value of one changes to random.

package main

import (
	"fmt"
)

func some(check interface{}) {
	check = "random"
}

func main() {
	var one *interface{}
	some(one)
	fmt.Println(one)
}

Specifically, I need ways in which I can pass an interface pointer to a function which accepts an interface as an argument.

Thanks!

答案1

得分: 12

  1. interface{}的指针作为some的第一个参数接受。
  2. one的地址传递给some
package main

import (
	"fmt"
)

func some(check *interface{}) {
	*check = "random"
}

func main() {
	var one interface{}
	some(&one)
	fmt.Println(one)
}

如果你想保持some的相同签名,你将需要使用reflect包来设置interface{}指针的值:

package main

import (
	"fmt"
	"reflect"
)

func some(check interface{}) {
	val := reflect.ValueOf(check)
	if val.Kind() != reflect.Ptr {
		panic("some: check must be a pointer")
	}
	val.Elem().Set(reflect.ValueOf("random"))
}

func main() {
	var one interface{}
	some(&one)
	fmt.Println(one)
}

注意:如果传递的值不能赋值给check指向的类型,val.Elem().Set()会引发恐慌。

英文:
  1. Accept a pointer to interface{} as the first parameter to some
  2. Pass the address of one to some

<!-- -->

package main

import (
	&quot;fmt&quot;
)

func some(check *interface{}) {
	*check = &quot;random&quot;
}

func main() {
	var one interface{}
	some(&amp;one)
	fmt.Println(one)
}

https://play.golang.org/p/ksz6d4p2f0

If you want to keep the same signature of some, you will have to use the reflect package to set the interface{} pointer value:

package main

import (
	&quot;fmt&quot;
	&quot;reflect&quot;
)

func some(check interface{}) {
	val := reflect.ValueOf(check)
	if val.Kind() != reflect.Ptr {
		panic(&quot;some: check must be a pointer&quot;)
	}
	val.Elem().Set(reflect.ValueOf(&quot;random&quot;))
}

func main() {
	var one interface{}
	some(&amp;one)
	fmt.Println(one)
}

https://play.golang.org/p/ocqkeLdFLu

Note: val.Elem().Set() will panic if the value passed is not assignable to check's pointed-to type.

huangapple
  • 本文由 发表于 2017年6月30日 05:32:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/44835313.html
匿名

发表评论

匿名网友

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

确定