登录
首页 >  Golang >  Go问答

传入一个函数来调用另一个函数

来源:stackoverflow

时间:2024-04-04 14:00:34 104浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《传入一个函数来调用另一个函数》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

您好,我有 2 个看起来相似的函数,我想创建一个通用函数。我的问题是:我不确定如何传递另一个函数:

func (b *business) streamhandler1(sm streams.stream, p []*types.people) {
    guard := make(chan struct{}, b.maxmanifestgoroutines)
    for _, person := range p {
        guard <- struct{}{} // would block if guard channel is already filled
        go func(n *types.people) {
            b.peoplehandler(sm, n)
            <-guard
        }(person)
    }
}

func (b *business) streamhandler2(sm streams.stream, pi []*types.peopleinfo) {
    guard := make(chan struct{}, b.maxmanifestgoroutines)
    for _, personinfo := range pi {
        guard <- struct{}{} // would block if guard channel is already filled
        go func(n *types.peopleinfo) {
            b.peopleinfohandler(sm, n)
            <-guard
        }(personinfo)
    }
}

您可以看到它们看起来非常非常相似,所以我想制作一个通用函数,可以在 peopleinfohandler peoplehandler 中传递。知道我怎样才能正确地做到这一点吗?看起来 go 的语法我应该能够做这样的事情:

func (b *Business) StreamHandler1(f func(streams.Stream, interface{}), sm streams.Stream, p []*interface{}) {

但这似乎不起作用。关于如何使其通用的任何想法?


解决方案


您可以使用定义的特定接口类型为传递的类型创建抽象。

我使用 peopler 接口来获取 people 或 peopleinfo,基于我定义的处理程序并将其传递给新的 streamhandler。如果您需要任何字段/方法,您也可以在处理程序中传递 *business

但正如 sergio 所说,如果该方法只有 5 行长,即使它大部分相同,也可能不值得。

对于具有保护结构的模式,您可以使用更适合的 sync.waitgroup

package main

import (
    "fmt"
    "time"
)


func (b *Business) StreamHandler(sm streamsStream, p []Peopler, handler func(streamsStream, Peopler)) {
    guard := make(chan struct{}, b.maxManifestGoRoutines)
    for _, person := range p {
        guard <- struct{}{} // would block if guard channel is already filled
        go func(p Peopler) {
            handler(sm, p)
            <-guard
        }(person)
    }
}

func peopleInfoHandler(s streamsStream, p Peopler) {
    fmt.Println("info:", p.PeopleInfo())
}

func peopleHandler(s streamsStream, p Peopler) {
    fmt.Println("people:", p.People())
}

func main() {
    b := &Business{maxManifestGoRoutines: 2}
    s := streamsStream{}
    p := []Peopler{
        &People{
            Info: PeopleInfo{Name: "you"},
        },
    }
    b.StreamHandler(s, p, peopleInfoHandler)
    b.StreamHandler(s, p, peopleHandler)

    time.Sleep(time.Second)
}

type streamsStream struct {
}

type People struct {
    Info PeopleInfo
}

func (tp *People) People() People {
    return *tp
}

type PeopleInfo struct {
    Name string
}

func (tp *People) PeopleInfo() PeopleInfo {
    return tp.Info
}

type Peopler interface {
    People() People
    PeopleInfo() PeopleInfo
}

type Business struct {
    maxManifestGoRoutines int
}

play link

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>