Create an instance of struts

Greetings:
Having issues creating var with an existing instance of structs.

The code snippet is below:
import (
“fmt”
“reflect”
)

type Product struct {
Name string
Price string
}
func main() {
p := Product{Name: “Hello”}
fmt.Println(p)
var data []p // This is causing issues
fmt.Println(data)
}

Can someone help me with this as I am stuck up? Need to create an Array of type Product. I do not want to use var data []Product directly as I have multiple structs and use an instance of structs.

Please help. Thanks!

Hi, Param, and welcome to the forum.

Can you clarify what you mean by:

Do you mean that you want a slice with p inside it, in which case, you can write this:

data := []Product{p}

If not, can you clarify what you would like the result to be?

Thanks, Sean!
The requirement is to create an array with an existing instance of Product that is p instead of using struct (Product) directly.
I could have done var data []Product and that would be fine. But, I need to do something like var data []p
I would pass an instance of Product and/or other structs using a function as an interface and do the rest of the coding.

Here is the complete code snippet:
package main

import (
“fmt”
“reflect”
)

type Product struct {
Name string
Price string
}
type Person struct {
Name string
address string
}

func somefunction(t interface{}) {

fmt.Println(reflect.TypeOf(t))
//data : = []reflect.TypeOf(t)
data := []t
fmt.Println(data)

}

func main() {
product := Product{Name: “Hello”}
fmt.Println(product)
somefunction(product)

person := Person {Name: "King"}
fmt.Println(person)
somefunction(person)

}

Get the following error message:
./prog.go:21:10: []t (type) is not an expression
./prog.go:21:12: t (variable of type interface{}) is not a type

I’m still not sure what you’re trying to do, but does this help: Go Playground - The Go Programming Language

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.