go - golang的 "range interface"是如何在内部运行的?

标签 go

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)

}

我不知道“range phones”在内部运行。我只知道“phone”按“[5]phone”顺序运行,我想知道 golang 如何识别 iphone 或 NokiaPhone。

谢谢,请原谅我蹩脚的英语。

最佳答案

接口(interface)是契约的声明,即实现实例必须支持的行为。通过提供在接口(interface)上定义的方法,Go 中的 struct 会自动实现该接口(interface),并且可以在任何基于接口(interface)的声明存在的地方使用该接口(interface)来代替该接口(interface)。这与许多其他语言(如 Java 或 C++)略有不同,在这些语言中,实例必须显式声明它实现的接口(interface)和它扩展的类。在运行时,代码将获取具体实例并执行该实例的方法。对于编码器或声明来说,这并不重要,重要的是该实例将具有在接口(interface)上定义的方法,并且可以调用该方法,因此可以用通用接口(interface)术语编写代码。

这种接受接口(interface)并提供结构/实例的想法是控制反转和依赖注入(inject)的核心。

这正是您示例中发生的情况。 NokiaPhoneIPhone 通过提供在接口(interface)Phone 上声明的方法来实现Phone 接口(interface)。当谈到循环时,在每次迭代中都会从数组中取出一个具体实例,对于该实例类型,查找代码中要求的方法,因此现在执行并执行。它在 Go、Java、C++(使用虚拟方法)和许多其他支持继承或接口(interface)/实现模式的语言中的工作方式与 Go 相同。

关于go - golang的 "range interface"是如何在内部运行的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49206841/

相关文章:

regex - HostRegexp 失败

go - Go lang函数返回多个值如何使用可变参数传递给其他函数

go - 为什么 Go 中的 big int api 这么奇怪?

go - 为什么在 regex.ReplaceAllString() 中删除数字

go - GoSNMP 中的对象名称而不是 OID

unit-testing - 您将如何对一个唯一目的是进行数据库调用的方法进行单元测试?

go - 如何让 k8s 按照特定规则分配 gpu/npu 设备

go - Golang反射: Inspect a struct type definition to extract its properties without initialization

amazon-web-services - 如何在 Go 中验证来自 AWS Cognito 的 JWT token ?

使用 goroutine 去 WaitGroup