gpt4 book ai didi

go - 从 golang 包中导出接口(interface)而不是结构

转载 作者:IT王子 更新时间:2023-10-29 01:19:18 27 4
gpt4 key购买 nike

您可以在下面找到调用客户结构的方法 Name() 的三种不同方式。结果完全相同,但三个包中的每一个都导出不同的东西:

package main

import (
"customer1"
"customer2"
"customer3"
"fmt"
"reflect"
)

func main() {

c1 := customer1.NewCustomer("John")
fmt.Println(c1.Name())

c2 := customer2.NewCustomer("John")
fmt.Println(c2.Name())

c3 := customer3.NewCustomer("John")
fmt.Println(c3.Name())
}

输出

John
John
John

customer1.go(导出 Customer 结构和 Name() 方法)

package customer1

type Customer struct {
name string
}

func NewCustomer(name string) * Customer{
return &Customer{name: name}
}

func (c *Customer) Name() string {
return c.name
}

customer2.go(不导出客户结构。仅导出 Name() 方法)

package customer2

type customer struct {
name string
}

func NewCustomer(name string) *customer {
return &customer{name: name}
}

func (c *customer) Name() string {
return c.name
}

customer3.go(不导出客户结构。导出客户接口(interface))

package customer3

type Customer interface {
Name() string
}
type customer struct {
name string
}

func NewCustomer(name string) Customer {
return &customer{name: name}
}

func (c *customer) Name() string {
return c.name
}

我的问题是您会推荐哪种方法,为什么?在可扩展性和可维护性方面哪个更好?您会在大型项目中使用哪一个?

官方不鼓励使用 customer3 方法(//不要这样做!!!),您可以在此处阅读 https://github.com/golang/go/wiki/CodeReviewComments#interfaces

最佳答案

Go 中的接口(interface)工作(和使用)与您使用其他语言(例如 Java)时所期望的有所不同。

在 Go 中,实现接口(interface)的对象不需要显式说它实现了它。

这会产生微妙的影响,例如即使实现方不打扰(或考虑)创建一个类型的消费者也能够与实现分离首先是一个界面。

因此,Go 中惯用的方法是使用第一种方法的变体。

您将完全按照您所做的方式定义 customer1.go(因此该类型的实现尽可能简单)。

然后如有必要您可以通过在其中定义一个接口(interface)来解耦消费者(在这种情况下是您的包):

type Customer interface {
Name() string
}

func main() {

var c1 Customer
c1 := customer1.NewCustomer("John")
fmt.Println(c1.Name())

}

这样,您的 main 实现可以与任何具有 Name() 方法的类型一起工作,即使最初实现该类型的包没有想到关于那个需要。

为了实现可扩展性,这通常也适用于您导出的接收参数的函数。

如果您要导出这样的函数:

func PrintName(customer Customer) {
fmt.Println(customer.Name())
}

然后可以使用任何实现 Customer 的对象调用该函数(例如,您的任何实现都可以工作)。

关于go - 从 golang 包中导出接口(interface)而不是结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51031116/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com