【问题标题】:Why is a function literal returning an int not assignable to a function returning interface{}? [duplicate]为什么返回 int 的函数文字不能分配给返回 interface{} 的函数? [复制]
【发布时间】:2019-09-27 03:06:54
【问题描述】:

我无法解释为什么这段代码会编译 not

package main

import "math/rand"

type ooThinAir func() interface{}

func Int() ooThinAir {
    return func() int {
        return rand.Intn(100)
    }
}
func main() {
}

// fails with: cannot use func literal (type func() int) as type ooThinAir in return argument

根据 GoLang 规范,that 所有类型都实现了空接口 interface{}。为什么函数文字 not 可分配给类型 ooThinAir

【问题讨论】:

  • ooThinAir 不是interface{}。如果是 (play.golang.org/p/x_pVwLdf3NS),那没关系,但事实并非如此。
  • A func() int 不能分配给 func() interface{}。使用这个:return func() interface{} { return rand.Intn(100) }.

标签: go


【解决方案1】:

任何类型都可以分配给接口。

包含接口的类型是另一回事。

[]int 不能分配给[]interface{}

func() int 不能分配给func() interface{}

你必须将整个东西变成interface{},然后使用反射来处理结果。

因为[]int 可以分配给interface{},而func() int 可以分配给interface{}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-08
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    • 2018-01-12
    • 2019-05-04
    相关资源
    最近更新 更多