Use reflect to make a new struct from unknown struct type

I have a function that expects to receive an array of pointers to structs of unknown definitions. I want to be able to create a new instance of the unknown struct, assign values to it, and then append it to the given array.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// Someone using this package example:
type Foo Struct {
Val int
Nested []Bar
}
type Bar struct {
Val int
}
func main() {
var foos []*Foo
Mutate(&foos)
// Expect foos[0] to be:
// Foo{Val: 1, Nested: { Bar{Val: 2} } }
}
// My function (no access to definition of Foo)
func Mutate(target any) {
// This is where i am stuck
t := reflect.TypeOf(target).Elem()
// => []*main.Foo
// I have no idea of how to create a new instance
// of main.Foo or even see what fields it has.
}
</code>
<code>// Someone using this package example: type Foo Struct { Val int Nested []Bar } type Bar struct { Val int } func main() { var foos []*Foo Mutate(&foos) // Expect foos[0] to be: // Foo{Val: 1, Nested: { Bar{Val: 2} } } } // My function (no access to definition of Foo) func Mutate(target any) { // This is where i am stuck t := reflect.TypeOf(target).Elem() // => []*main.Foo // I have no idea of how to create a new instance // of main.Foo or even see what fields it has. } </code>
// Someone using this package example:
type Foo Struct {
    Val int
    Nested []Bar
}

type Bar struct {
   Val int
}

func main() {
    var foos []*Foo
    Mutate(&foos)
    
    // Expect foos[0] to be:
    // Foo{Val: 1, Nested: { Bar{Val: 2} } }
}

// My function (no access to definition of Foo)
func Mutate(target any) {
    // This is where i am stuck
    t := reflect.TypeOf(target).Elem()
    // => []*main.Foo
    // I have no idea of how to create a new instance 
    // of main.Foo or even see what fields it has.
}

Try this code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>func Mutate(target any) {
// Get reflect.Value for slice.
slice := reflect.ValueOf(target).Elem()
// Create pointer to value. Set a field in the value.
valuet := slice.Type().Elem().Elem()
valuep := reflect.New(valuet)
value := valuep.Elem()
value.FieldByName("Val").SetInt(1)
// Append value pointer to slice set resulting slice
// in target.
slice.Set(reflect.Append(slice, valuep))
}
</code>
<code>func Mutate(target any) { // Get reflect.Value for slice. slice := reflect.ValueOf(target).Elem() // Create pointer to value. Set a field in the value. valuet := slice.Type().Elem().Elem() valuep := reflect.New(valuet) value := valuep.Elem() value.FieldByName("Val").SetInt(1) // Append value pointer to slice set resulting slice // in target. slice.Set(reflect.Append(slice, valuep)) } </code>
func Mutate(target any) {
    // Get reflect.Value for slice.
    slice := reflect.ValueOf(target).Elem()

    // Create pointer to value. Set a field in the value.
    valuet := slice.Type().Elem().Elem()
    valuep := reflect.New(valuet)
    value := valuep.Elem()
    value.FieldByName("Val").SetInt(1)

    // Append value pointer to slice set resulting slice
    // in target.       
    slice.Set(reflect.Append(slice, valuep))
}

https://play.golang.com/p/fAxkHexQheC

New contributor

Jeremy Bender is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

0

While Jeremys answer goes in the right direction, the resulting foos[0] is Foo{Val: 1, Nested: nil }. Setting hierarchical values via reflect can be tricky, so may I suggest using JSON for this?

First generate an new Foo value and append it to the slice:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> t := reflect.ValueOf(target).Elem()
foo := reflect.New(t.Type().Elem().Elem())
t.Set(reflect.Append(t, foo))
</code>
<code> t := reflect.ValueOf(target).Elem() foo := reflect.New(t.Type().Elem().Elem()) t.Set(reflect.Append(t, foo)) </code>
    t := reflect.ValueOf(target).Elem()
    foo := reflect.New(t.Type().Elem().Elem())
    t.Set(reflect.Append(t, foo))

then use JSON so fill in the value Foo{Val:1 Nested:[Bar{Val:2}]}:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> v := `{"Val":1,"Nested":[{"Val":2}]}`
if err := json.Unmarshal([]byte(v), foo.Interface()); err != nil {
log.Fatal(err) // do some reasonable error handling here
}
</code>
<code> v := `{"Val":1,"Nested":[{"Val":2}]}` if err := json.Unmarshal([]byte(v), foo.Interface()); err != nil { log.Fatal(err) // do some reasonable error handling here } </code>
    v := `{"Val":1,"Nested":[{"Val":2}]}`
    if err := json.Unmarshal([]byte(v), foo.Interface()); err != nil {
        log.Fatal(err) // do some reasonable error handling here
    }

See the result on the Go Playground.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật