从 Go 中的可变参数创建带有可选字段的类型

Creating a type with optional fields from variadic arguments in Go

我现在正在学习 Go,并且想在不使用反射的情况下使用可变参数初始化一个类型。可能吗?

举个例子:

type MyType struct {
    field1 string
    field2 string
    ...
    fieldN string
}

func CreateMyType(arguments ...string) *MyType {
    inst := MyType{arguments...}  // does not work, is there any other way???
    return &inst
}

注意 这让我很难过,这个问题被否决了,我问的是合法的东西,并试图从中学习:(

一点代码就可以做到:

func CreateMyType(arguments ...string) *MyType {
    var m MyType
    switch len(arguments) {
    case 3:
        m.field3 = arguments[2]
        fallthrough
    case 2:
        m.field2 = arguments[1]
        fallthrough
    case 1:
        m.field1 = arguments[0]
    }
    return &m
}

playground example