dongliu6848 2016-12-28 23:18
浏览 91
已采纳

如何使用interface {}将整数作为指针传递给函数

I thought this is a simple thing to do, but I was wrong. I can't pass integer as pointer to function using interface{}.

Example:

var test int
someChange(&test)
fmt.Printf("after function: %d", test)

func someChange(i interface{}) error{
    newFunnyValue := 42
    i = newFunnyValue
    fmt.Printf("hello from someChange now value test is: %d" , i)
    return nil //change gone ok, so nil
}

And result:

 hello from someChange now value test is: 42 
 after function: 0

I read that interface{} is similar to void* so above code should work but it's not, why? I want to add that if I pass some object which is a struct, everything works good.

Do I have to wrap int in some struct?

Edit:

https://play.golang.org/p/rg1vabug0P

  • 写回答

2条回答 默认 最新

  • duanhui3759 2016-12-28 23:55
    关注

    If you want to observe the change outside of the someChange() function (in the test variable), you must modify the pointed value (assign a new value to it). You're not doing that, you just assign a new value to the i parameter (which is a local variable inside someChange()).

    You may obtain the *int pointer from the i interface variable using type assertion, and then you can assign a new value to the pointed value.

    Example:

    func someChange(i interface{}) error {
        newFunnyValue := 42
        if p, ok := i.(*int); ok {
            *p = newFunnyValue
            return nil //change gone ok, so nil
        }
        return errors.New("Not *int")
    }
    

    Testing it:

    var test int
    someChange(&test)
    log.Printf("after function: %d", test)
    

    Output (try it on the Go Playground):

    2009/11/10 23:00:00 after function: 42
    

    Note that wrapping the int value or the *int pointer in a struct is unnecessary and it wouldn't make a difference if you're not assigning a new value to the pointed object.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用