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.

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

报告相同问题?

悬赏问题

  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding