Golang embedded struct type

后端 未结 3 1339
醉话见心
醉话见心 2020-12-03 03:07

I have these types:

type Value interface{}

type NamedValue struct {
    Name  string
    Value Value
}

type ErrorValue struct {
    NamedValue
    Error er         


        
3条回答
  •  一个人的身影
    2020-12-03 03:47

    For deeply nested structs, the accepted answer's syntax is a little verbose. For example, this :

    package main
    
    import (
        "fmt"
    )
    
    type Alternative struct {
        Question
        AlternativeName string
    }
    
    type Question struct {
        Questionnaire
        QuestionName  string
    }
    
    type Questionnaire struct {
        QuestionnaireName string
    }
    
    func main() {
        a := Alternative{
            Question: Question{
                Questionnaire: Questionnaire{
                    QuestionnaireName: "q",
                },
            },
        }
        fmt.Printf("%v", a)
    }
    

    (Go playground)

    Could be rewritten like this:

    a := Alternative{}
    a.QuestionnaireName = "q"
    

提交回复
热议问题