doupu3635 2017-11-10 13:58
浏览 15

接口如何具有可比性,而同时又不能发挥作用?

I have the following code-snippet:

type F func()

type I interface {}

func A() {}

func B() {}

func test() {
    var a interface{} = A
    var b interface{} = B
    if A == B { // 1. Compile error 
        // Code
    }

    if a == b { // 2. No compile error
        // Code
    }
}

If functions are not comparable and interfaces are comparable, why can I assign a function to an interface type?

--

To clarify my question another code-snippet:

type I interface {
    DoSomething()
}

type F func()

func (f F) DoSomething() {
    f()
}

func A() {
    fmt.Println("A")
}

func B() {
    fmt.Println("B")
}

func test() {
    var _a F = A
    var _b F = B
    var a I = _a
    var b I = _b

    if a == b { // 2. No compile error but panic
        // Code
    }
}

It seems to me, that I can break the type system with simple assignments.

I do not propose that functions should be comparable. My questions are:

  • Why interfaces are comparable by default?
  • Why is it not possible to mark an interface as comparable resp. not comparable?
  • Why is it not possible do define user defined-equality?
  • What is the motivation in this language design?
  • 写回答

2条回答 默认 最新

  • duanhuo3392 2017-11-10 14:16
    关注

    This is simply how the language is defined. From the spec:

    Interface values are comparable. Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil.

    A comparison of two interface values with identical dynamic types causes a run-time panic if values of that type are not comparable.

    function values are not comparable. However, as a special case, a [...] function value may be compared to the predeclared identifier nil.

    That explains why the first if statement in your example fails at compile time, and why the second one fails at runtime.

    评论

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错