dongxie5698 2018-03-10 08:10
浏览 38
已采纳

golang的“范围接口”如何在内部运行?

package main

import "fmt"

type Phone interface {
    call()
    sales() int
}

type NokiaPhone struct {
    price int
}

func (nokiaPhone NokiaPhone) call() {
    fmt.Println("I am Nokia, I can call you!")
}
func (nokiaPhone NokiaPhone) sales() int {
    return nokiaPhone.price
}

type IPhone struct {
    price int
}

func (iPhone IPhone) call() {
    fmt.Println("I am iPhone, I can call you!")
}

func (iPhone IPhone) sales() int {
    return iPhone.price
}

func main() {
    var phones = [5]Phone{
        NokiaPhone{price: 350},
        IPhone{price: 5000},
        IPhone{price: 3400},
        NokiaPhone{price: 450},
        IPhone{price: 5000},
    }

    var totalSales = 0
    **for _, phone := *range phones* {
        totalSales += phone.sales()
    }**
    fmt.Println(totalSales)

}

i don't know the "range phones" run internally.i only understand that 'phone' is run in '[5]phone' order and i want to konw that golang how to recognizes iphone or NokiaPhone.

Thanks , forgive me for my lame English.

  • 写回答

1条回答 默认 最新

  • dqwh1202 2018-03-10 08:26
    关注

    An interface is a declaration of a contract, that is of the behaviour that implementing instances must support. By providing methods that are defined on the interface, a struct in Go automatically implements that interface and can be used in place of that interface wherever an interface based declaration is present. This is slightly different from many other languages such as Java or C++ where an instance must explicitly declare interfaces it implements and classes it extends. At runtime the code will get a concrete instance and execute a method of that instance. For the coder or for the declaration it does not matter, what matters is that instance will have a method as defined on the interface and that method can be called so the code can be written in generic interface terms.

    This idea to accept interfaces and provide structs/instances is central for the inversion of control and dependency injection.

    This is exactly what happens in you example. NokiaPhone and IPhone implement the Phone interface by providing methods declared on the interface Phone. When it comes to the loop, at each iteration a concrete instance is taken out of array, for that instance type the method asked for in the code is looked up, so the implementation now, and is executed. It works in the same way in Go, Java, C++ (with virtual methods) and many other languages that support either inheritance or interface/implementation pattern as Go does.

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

报告相同问题?

悬赏问题

  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan