英文:
How to pass interface of struct type by reference in golang?
问题
我需要将一个结构体类型的接口通过引用传递,如下所示。由于我不能使用指向结构体类型变量的接口指针,我应该如何修改下面的代码,将te
的值修改为10
?
package main
import (
"fmt"
)
func another(te *interface{}) {
*te = check{Val: 10}
}
func some(te *interface{}) {
*te = check{Val: 20}
another(te)
}
type check struct {
Val int
}
func main() {
a := check{Val: 100}
p := &a
fmt.Println(*p)
some(p)
fmt.Println(*p)
}
谢谢!
附注:我已经阅读到传递接口指针不是一个很好的做法。请告诉我如何更好地处理它。
英文:
I need to pass an interface of a struct type by reference as shown below. Since, I can't use pointers of interface to struct type variables, how should I change the below code to modify te
value to 10
?.
package main
import (
"fmt"
)
func another(te *interface{}) {
*te = check{Val: 10}
}
func some(te *interface{}) {
*te = check{Val: 20}
another(te)
}
type check struct {
Val int
}
func main() {
a := check{Val: 100}
p := &a
fmt.Println(*p)
some(p)
fmt.Println(*p)
}
Thanks!
P.S I have read that passing pointers to interfaces is not a very good practice. Kindly let me know what could be a better way to handle it
答案1
得分: 14
所以你正在使用一个接口,并且你需要一种保证,能够设置结构体成员的值?听起来你应该将这种保证作为接口的一部分,可以这样做:
type Settable interface {
SetVal(val int)
}
func (c *check) SetVal(val int) {
c.Val = val
}
func some(te Settable) {
te.SetVal(20)
}
type check struct {
Val int
}
func main() {
a := check{Val: 100}
p := &a
some(p)
fmt.Println(*p)
}
英文:
So you're using an interface, and you need some sort of guarantee that you can set the value of a member of the struct? Sounds like you should make that guarantee part of the interface, so something like:
type Settable interface {
SetVal(val int)
}
func (c *check) SetVal(val int) {
c.Val = val
}
func some(te Settable) {
te.SetVal(20)
}
type check struct {
Val int
}
func main() {
a := check{Val: 100}
p := &a
some(p)
fmt.Println(*p)
}
答案2
得分: 0
以下类似的代码应该可以工作:
func some(te interface{}) {
switch te.(type) {
case *check:
*te.(*check) = check{Val: 20}
}
}
请注意,这是一段Go语言代码,用于类型断言和类型转换。根据传入的参数类型,它将执行不同的操作。在这个例子中,如果te
的类型是*check
指针类型,它将将Val
字段的值设置为20。
英文:
Something similar to the below should work
func some(te interface{}) {
switch te.(type) {
case *check:
*te.(*check) = check{Val: 20}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论