自关联数据demo

package main

import (
    "log"
)

type A struct {
    Id   int
    Name string
    AId  int
    A    *A
}

func main() {
    a := GetById(1, GetByIdFunc())
    log.Println(a)
}

func GetById(id int, iniAFunc func(a *A)) *A {
    log.Println("id:", id)
    a := new(A)
    switch id {
    case 1:
        a.Id = 1
        a.Name = "a1"
        a.AId = 2
    case 2:
        a.Id = 2
        a.Name = "a2"
        a.AId = 3
    case 3:
        a.Id = 3
        a.Name = "a3"
        a.AId = 0
    }
    iniAFunc(a)
    return a
}

func GetByIdFunc() func(a *A) {
    return func(a *A) {
        switch a.AId {
        case 0:
            return
        default:
            a.A = GetById(a.AId, GetByIdFunc())
        }
    }
}

你可能感兴趣的:(自关联数据demo)