问题描述
te 10
te10
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)
}
谢谢!
P.S我已经读过,将指针传递给接口并不是一种很好的做法.请让我知道有什么更好的处理方法
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
推荐答案
因此,您正在使用接口,并且需要某种保证可以设置结构成员的值吗?听起来您应该使该保证成为界面的一部分,所以类似:
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)
}
这篇关于如何在Golang中通过引用传递结构类型的接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!