如何在Golang中通过引用传递结构类型的接口? [英] How to pass interface of struct type by reference in golang?

查看:63
本文介绍了如何在Golang中通过引用传递结构类型的接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过引用传递结构类型的接口,如下所示.由于不能使用接口指针构造类型变量,因此应如何更改以下代码以将 te 的值修改为 10 ?.

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

谢谢!

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆