简体   繁体   English

辅助函数将各自的数据分配给它的键

[英]Helper func to assign respective data to its key

So I have this data struct:所以我有这个数据结构:

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

type ChildA struct {
    ...

}

I am trying to create a helper funct such that I can reduce my LOC when it comes to variable assignment.我正在尝试创建一个辅助函数,以便在变量赋值时可以减少我的 LOC。

What I am trying to do:我正在尝试做的事情:

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

"?" “?” can be any of the key AB C D可以是任意键 AB C D

We can use variadic function and reflection.我们可以使用可变参数 function 和反射。

this is the 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 {
        childType := reflect.TypeOf(v)

        check[childType.Name()]++

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

        // use String() because we need to know module name
        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)
}

You can use Visitor pattern.您可以使用访客模式。

type Parent struct {
    A ChildA
    B ChildB
    C ChildC
}

type Child interface {
    VisitParent(*Parent)
}

type ChildA struct{}

func (c ChildA) VisitParent(parent *Parent) {
    parent.A = c
}

type ChildB struct{}

func (c ChildB) VisitParent(parent *Parent) {
    parent.B = c
}

type ChildC struct{}

func (c ChildC) VisitParent(parent *Parent) {
    parent.C = c
}

func SomeHelper(someChild Child) Parent {
    parent := Parent{}
    someChild.VisitParent(&parent)

    return parent
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM