a program to initialise a struct instance based on a set condition

PHOTO EMBED

Tue Nov 15 2022 16:56:47 GMT+0000 (Coordinated Universal Time)

Saved by @Plastikov #go

package main

import "fmt"

type commonPerson struct {
    A string
    B string
    C string
}

type PersonA struct {
    commonPerson
}

func (p PersonA) String() string {
    return fmt.Sprintf("A: %s, %s, %s", p.A, p.B, p.C)
}

// This function is just here so that PersonA implements personInterface
func (p PersonA) personMarker() {}

type PersonB struct {
    commonPerson
}

func (p PersonB) String() string {
    return fmt.Sprintf("B: %s, %s, %s", p.A, p.B, p.C)
}

// This function is just here so that PersonB implements personInterface
func (p PersonB) personMarker() {}

type personInterface interface {
    personMarker()
}

var smartPerson personInterface

func smartAction(personType string) {
    common := commonPerson{
        A: "foo",
        B: "bar",
        C: "Hello World",
    }

    switch personType {
    case "A":
        smartPerson = PersonA{commonPerson: common}
    case "B":
        smartPerson = PersonB{commonPerson: common}
    }
}

func main() {
    smartAction("A")
    fmt.Println(smartPerson)
    smartAction("B")
    fmt.Println(smartPerson)
}
content_copyCOPY

https://stackoverflow.com/questions/70778524/go-how-to-create-and-initialize-a-struct-instance-based-on-conditions-when-the