I have a requirement in which I need to store array of objects in a variable. The objects are of different types. Refer to following example:
v := [ {"name":"ravi"},
["art","coding","music","travel"],
{"language":"golang"},
{"experience":"no"}
]
Notice the second element is array of string itself. After research, I thought of storing this as interface type like:
var v interface{} = [ {"name":"ravi"},
["art","coding","music","travel"],
{"language":"golang"},
{"experience":"no"}
]
Still, I am getting few compilation errors which I am not able to find out.
In the code above: Line 3: We import the fmt package. Line 7: Inside the main() function, we use := to declare an array marks of type int and length 5 . Line 10: We output the marks array on the console.
You can initialize an array with pre-defined values using an array literal. An array literal have the number of elements it will hold in square brackets, followed by the type of its elements. This is followed by a list of initial values separated by commas of each element inside the curly braces.
To create an array you'd use [N]type{42, 33, 567} or [...] type{42, 33, 567} — to get the size inferred from the number of member in the initializer. ^Sure, I guess in Go you use arrays so rarely and the syntax is so similar that I basically interchange the two even if they are different things.
Creating and accessing an Array In Go language, arrays are mutable, so that you can use array[index] syntax to the left-hand side of the assignment to set the elements of the array at the given index. You can access the elements of the array by using the index value or by using for loop.
What you're asking for is possible -- playground link:
package main
import "fmt"
func main() {
v := []interface{}{
map[string]string{"name": "ravi"},
[]string{"art", "coding", "music", "travel"},
map[string]string{"language": "golang"},
map[string]string{"experience": "no"},
}
fmt.Println(v)
}
But you probably don't want to be doing this. You're fighting the type system, I would question why you're using Go if you were doing it like this. Consider leveraging the type system -- playground link:
package main
import "fmt"
type candidate struct {
name string
interests []string
language string
experience bool
}
func main() {
candidates := []candidate{
{
name: "ravi",
interests: []string{"art", "coding", "music", "travel"},
language: "golang",
experience: false,
},
}
fmt.Println(candidates)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With