dongtan4046 2017-06-26 18:26
浏览 66
已采纳

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

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条回答 默认 最新

  • dongqiang2024 2017-06-26 18:37
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?