结构体内的函数。为什么?

huangapple go评论78阅读模式
英文:

A function within a structure. Why?

问题

在Go语言中,在结构体内定义函数的用例/优势是什么?

type demo struct {
    F func()
}

在这个示例中,结构体demo包含了一个函数类型的字段F。这种方式允许我们在结构体内部定义一个函数,并将其作为结构体的一部分。

这种用法的优势之一是可以将函数与特定的结构体实例关联起来。通过在结构体内定义函数,我们可以在创建结构体实例时,将特定的函数赋值给结构体的字段。这样,我们可以将函数与结构体实例绑定在一起,方便地访问和操作。

此外,将函数定义在结构体内部还可以实现封装和隐藏。通过将函数定义在结构体内部,我们可以限制函数的可见性,只允许结构体内部的其他方法或函数访问该函数。这样可以提高代码的安全性和可维护性。

总而言之,通过在结构体内定义函数,我们可以实现函数与结构体实例的关联,并实现封装和隐藏的效果,从而提高代码的可读性和可维护性。

英文:

What is the use case/advantage of defining a function within a structure in go?

type demo struct {
	F func()
}

答案1

得分: 6

我认为最好的答案是一个示例。

请查看文档中的 Client.CheckRedirect

type Client struct {
    // (...)
    CheckRedirect func(req *Request, via []*Request) error
}

这是一个在 http.Client 有重定向响应时被调用的函数。由于这个函数是一个公共属性,你可以在创建 Client 对象时或之后设置它,从而定义在这种情况下的自定义行为。

client := &http.Client{
    CheckRedirect: func(req *http.Request, via []*http.Request) error {
        return http.ErrUseLastResponse
    }
}

函数属性只是自定义行为的委托(不仅仅如此!)。

另一个示例是创建一个具有事件的对象。

type Example struct {
    EventHandler func(params []interface{})
}

通过设置 Example.EventHandler 属性,你可以指定该事件的行为。

英文:

I think that the best answer would be an example.

Look at Client.CheckRedirect in the documentation.

type Client struct {
    // (...)
    CheckRedirect func(req *Request, via []*Request) error
}

This is a function that is being invoked whenever a http.Client has a redirect response. By the fact, that this function is a public property, you can set this when creating the Client object or afterwards and thus you can define custom behaviour on such case.

client := &http.Client{
    CheckRedirect: func(req *http.Request, via []*http.Request) error {
        return http.ErrUseLastResponse
    }
}

Function properties are just a delegates of custom behaviour (and not only!).

Another example would be creating an object which has an event.

type Example struct {
    EventHandler func(params []interface{})
}

You can specify a behaviour on that event by setting the Example.EventHandler property.

答案2

得分: -1

它允许您自定义一个类型的函数,而无需将其作为该类型的一部分。

英文:

It allows you to customize the function for a type without making it be from that type.

huangapple
  • 本文由 发表于 2017年7月29日 19:37:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/45388814.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定