英文:
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
- 将
interface{}
的指针作为some
的第一个参数接受。 - 将
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()
会引发恐慌。
英文:
- Accept a pointer to
interface{}
as the first parameter tosome
- Pass the address of
one
tosome
<!-- -->
package main
import (
"fmt"
)
func some(check *interface{}) {
*check = "random"
}
func main() {
var one interface{}
some(&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 (
"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)
}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论