如何在Golang中通过引用传递结构类型的接口?

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

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

huangapple
  • 本文由 发表于 2017年6月27日 02:26:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/44766284.html
匿名

发表评论

匿名网友

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

确定