【问题标题】:Helper func to assign respective data to its key辅助函数将各自的数据分配给它的键
【发布时间】:2022-08-23 21:13:14
【问题描述】:

所以我有这个数据结构:

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

  • 使用反射(或尝试泛型)。

标签: go


【解决方案1】:

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

这是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)
}

【讨论】:

    【解决方案2】:

    您可以使用访客模式。

    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-16
      • 2021-07-25
      • 2020-01-30
      • 2016-04-16
      • 2017-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多