登录
首页 >  Golang >  Go问答

将数据分配给它的键的帮助函数

来源:stackoverflow

时间:2024-02-08 19:33:23 268浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《将数据分配给它的键的帮助函数》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

所以我有这个数据结构:

type parent struct {
    a childa
    b childb
    c childc
    d childd
}

type childa struct {
    ...

}

我正在尝试创建一个辅助函数,以便在变量赋值时可以减少 loc。

我正在尝试做的事情:

func SomeHelper( SomeChild Child? ) Parent {
    return Parent{
        ?: SomeChild
    }
}

“?”可以是任意键 a b c d


正确答案


我们可以使用可变参数函数和反射。

这是 example code

package main

import (
    "errors"
    "fmt"
    "reflect"
)

type Parent struct {
    A ChildA
    B ChildB
    C ChildC
    D ChildD
}

type ChildA struct {
    x string
}

type ChildB struct {
    x string
}

type ChildC struct {
}

type ChildD struct {
}

func helper(childs ...any) (Parent, error) {
    check := make(map[string]int)
    var p Parent

    for _, v := range childs {
        if v == nil {
            continue
        }
        childType := reflect.TypeOf(v)

        check[childType.String()]++

        if check[childType.String()] > 1 {
            return p, errors.New("child must be unique")
        }

        switch childType.String() {
        case "main.ChildA":
            p.A = v.(ChildA)
        case "main.ChildB":
            p.B = v.(ChildB)
        case "main.ChildC":
            p.C = v.(ChildC)
        case "main.ChildD":
            p.D = v.(ChildD)
        }
    }

    return p, nil
}

func main() {
    p, err := helper(ChildA{"hello"}, ChildB{"world"}, ChildC{})
    if err != nil {
        panic(err)
    }

    fmt.Println(p)
}

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

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