猿问

go - 写入接口的函数{}

我想将指向某个东西的指针传递给一个函数,而在编译时不知道它的类型,让函数写入它。这是我认为可行的方法:


func foo(dest interface{}) {

    switch (dest).(type) {

    case *int:

        fmt.Println("got int")

        *dest = 1

    // handle other cases...

    }

}

但是,使用*int输入调用它


func main() {

    bar := 2

    foo(&bar)

    fmt.Println(bar) // expect 1

}

产生编译器错误


invalid indirect of dest (type interface {}).


我在这里做错了什么?


守候你守候我
浏览 159回答 3
3回答

神不在的星期二

在这段代码中(顺便说一句,您不需要周围的括号dest),一旦输入案例,您基本上会忘记类型:func foo(dest interface{}) {    switch dest.(type) {    case *int:        fmt.Println("got int")        *dest = 1    // handle other cases...    }}也就是说,根据编译器, dest 仍然是 interface{} 类型,这是*dest = 1错误的。你可以使用更多这样的类型断言......func foo(dest interface{}) {    switch dest.(type) {    case *int:        fmt.Println("got int")        *dest.(*int) = 1        // handle other cases...    }}...但实际上“记住”类型的开关会好得多(来自Effective Go)func foo(dest interface{}) {    switch dest := dest.(type) {    case *int:        fmt.Println("got int")        *dest = 1    // handle other cases...    }}

杨__羊羊

dest 仍然是类型interface{}。您还必须在分配期间投射它:*dest.(*int) = 1

富国沪深

这个问题似乎有点老了,但我提出了一种使用反射来处理这个问题的更通用的方法,它不如其他解决方案快,但它适用于您传递给函数的任何其他类型func foo(dest interface{}) {    destVal := reflect.ValueOf(dest)    val := reflect.ValueOf(1)    if destVal.Kind() == reflect.Ptr && destVal.Elem().Kind() == val.Kind() {        if destElem := destVal.Elem(); destElem.CanSet() {            destElem.Set(val)        }    }}
随时随地看视频慕课网APP

相关分类

Go
我要回答