douzhongjian0752 2015-08-15 12:21
浏览 22
已采纳

go-写入接口的功能{}

I want to pass a pointer to something into a function, without knowing its type at compile time, have the function write to it. Here's what I thought would work:

func foo(dest interface{}) {
    switch (dest).(type) {
    case *int:
        fmt.Println("got int")
        *dest = 1
    // handle other cases...
    }
}

However, calling this with an *int input

func main() {
    bar := 2
    foo(&bar)
    fmt.Println(bar) // expect 1
}

yields the compiler error

invalid indirect of dest (type interface {}).

What am I doing wrong here?

  • 写回答

3条回答 默认 最新

  • doushan7997 2015-08-15 12:32
    关注

    In this piece of code (btw, you don't need the parens around dest), you are basically forgetting the type once you enter a case:

    func foo(dest interface{}) {
        switch dest.(type) {
        case *int:
            fmt.Println("got int")
            *dest = 1
        // handle other cases...
        }
    }
    

    That is, dest is still of type interface{} according to the compiler, and that makes *dest = 1 wrong.

    You could use more type assertions like this...

    func foo(dest interface{}) {
        switch dest.(type) {
        case *int:
            fmt.Println("got int")
            *dest.(*int) = 1
            // handle other cases...
        }
    }
    

    ...but a switch that actually 'remembers' the type would be much better (from Effective Go)

    func foo(dest interface{}) {
        switch dest := dest.(type) {
        case *int:
            fmt.Println("got int")
            *dest = 1
        // handle other cases...
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度