dqxz96998 2014-12-05 06:38
浏览 21
已采纳

Go界面中的设计决策{}

Why Go doesn't automatically convert between:

package main

import "fmt"

type Any interface{} // Any is an empty interface
type X func(x Any) // X is a function that receives Any

func Y(x X) { // Y is a function that receives X
  x(1)
}

func test(v interface{}) { // test is not considered equal to X
  fmt.Println("called",v)
}

func main() {
  Y(test) // error: cannot use test (type func(interface {})) as type X in argument to Y
}

Also this one:

package main
import "fmt"

type Any interface{}

func X2(a Any) {
  X(a)
} 
func Y2(a interface{}) {
  X2(a) // this is OK
}

func X(a ...Any) {
  fmt.Println(a)
}
func Y(a ...interface{}) { // but this one not ok
  X(a...) // error: cannot use a (type []interface {}) as type []Any in argument to X
}

func main() {
  v := []int{1,2,3}
  X(v)
  Y(v)
}

I was really hopeful that interface{} could be renamed to Any on anything (slices, map, func) not just simple types

Second question would be: is there a way to make it possible?

  • 写回答

1条回答 默认 最新

  • duanji2014 2014-12-05 06:43
    关注

    The first one is about type conversion and type identity, for which you have a set of rules.
    See more at "Why can I type alias functions and use them without casting?"

    • type Any interface{} is a named type
    • interface{} is an unnamed type

    Their identity is different, and you cannot use func(interface[}) in place of func(Any).


    The second one is covered by the golang faq

    Can I convert a []T to an []interface{}?

    Not directly, because they do not have the same representation in memory.
    It is necessary to copy the elements individually to the destination slice. This example converts a slice of int to a slice of interface{}:

    t := []int{1, 2, 3, 4}
    s := make([]interface{}, len(t))
    for i, v := range t {
        s[i] = v
    }
    

    See "what is the meaning of interface{} in golang?" for more on the memory representation:

    interface

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数