Print array values in Go - arrays

I'm trying to define an array in struct in Go, devices array should have 3 items of type strings, but I can't find out how to print values of devices array
Below outputs "mismatched types string and [2]string". Any hints?
type Nodes struct {
Nodes []Node `json:"nodes"`
}
type Node struct {
devices [2]string `json:"devices"`
}
var nodes Nodes
fmt.Println("Device: %+v" + nodes.Nodes[i].devices)

Your error is because you're trying to concatenate a string and a [2]string:
"Device: %+v" + nodes.Nodes[i].devices
Specifically, "Device: %+v" is a string, and nodes.Nodes[i].devices is a [2]string.
But at higher level, this is the result of improperly using fmt.Println, made apparent by the use of a formatting verb %+v, which makes no sense in the context of Println. What you probably want is fmt.Printf:
fmt.Printf("Device: %+v\n", nodes.Nodes[0].devices)

You have to use fmt.Printf instead of Println :
fmt.Printf("Device: %+v", nodes.Nodes[i].devices)
Or you can do something like this :
for _, node := range nodes.Nodes {
for _, device := range node.devices {
fmt.Println("Device : " + device)
}
}
The output :
Device : Android
Device : iOS

Related

Calling valiable name from another variable

Please help to call the variable from another variable.
I have the script which is taking EC2 instances and return in "*ec2.Instance" variable.
I can print information from static text, for example :
fmt.Println(instance.InstanceType) // t3.small
But I have the list of reqired fields like and don't know how dynamic use name from this list :
fields := []string{"InstanceId", "InstanceType", "PrivateIpAddress"}
for i := range fields {
fmt.Println(fields[i])
fmt.Println(instance.fields[i]) // Not correct ... :(
}
You need to use reflection to do this in go.
The key takeaway is you need to "analyze" the returned value at runtime and access properties by name from the "reflected" structure. Reflection basically means analyzing objects at runtime.
package main
import (
"fmt"
"reflect"
)
type whatever struct {
cat string
dog string
animals int
something string
}
func main() {
wantProps := []string{ "cat", "animals"}
we := whatever{cat: "meow", animals: 22}
r := reflect.ValueOf(we)
for _, propName := range wantProps {
prop := r.FieldByName(propName)
fmt.Println(propName, prop)
}
}
More details:
Golang dynamic access to a struct property

Golang nested struct slice - Error index out of range

Playground
I'm trying to store a string into a slice field inside a struct. This is for collecting data and create a Json to post via to an API.
package main
type response1 struct {
Identifier string `json:"identifier"`
Family string `json:"family"`
Values struct {
Logo []struct {
Data string `json:"data"`
Scope string `json:"scope"`
} `json:"logo"`
}
}
func main() {
res2D := &response1{
Identifier: "1234567",
Family: "example",
}
res2D.Values.Logo[0].Data = "test"
res2B, _ := json.Marshal(res2D)
fmt.Println(string(res2B))
}
Error
And the error I got:
panic: runtime error: index out of range
goroutine 1 [running]:
main.main()
/tmp/sandbox507443306/main.go:22 +0xe0
You do not have to make the slice with appropriate size before hand. You can use append. What you are trying to do in your example is assign a slice "[0]" that has not been created yet, which is why you are getting your error. Use append and change your line
res2D.Values.Logo[0].Data = "test"
to
res2D.Values.Logo = append(res2D.Values.Logo,struct {Data string "json:\"data\"" }{Data: "test"})
and that will append the literal struct into your array. Now by looking at your code I am assuming you doing this as a test to explore the language so I wont go into detail on how to better write this without knowing what you are actually using it for.

type interface {} does not support indexing in golang

I have such map:
Map := make(map[string]interface{})
This map is supposed to contain mapping from string to array of objects. Arrays can be of different types, like []Users or []Hosts. I populated this array:
TopologyMap["Users"] = Users_Array
TopologyMap["Hosts"] = Hosts_Array
but when I try to get an elements from it:
Map["Users"][0]
it gives an error:
(type interface {} does not support indexing)
How can I overcome it?
You have to explicitly convert your interface{} to a slice of the expected type to achieve it. Something like this:
package main
import "fmt"
type Host struct {
Name string
}
func main() {
Map := make(map[string]interface{})
Map["hosts"] = []Host{Host{"test.com"}, Host{"test2.com"}}
hm := Map["hosts"].([]Host)
fmt.Println(hm[0])
}
Playground link
First thing to be noted is the interface{} can hold any data type including function and struct or []struct. Since the error gives you :
(type interface {} does not support indexing)
It means that it holds no slice or no array values. Because you directly call the index in this case is 0 to an interface{} and you assume that the Map["Users"] is an array. But it is not. This is one of very good thing about Go it is statically type which mean all the data type is check at compiled time.
if you want to be avoid the parsing error like this:
panic: interface conversion: interface {} is []main.User, not
[]main.Host
To avoid that error while your parsing it to another type like Map["user"].([]User) just in case that another data type pass to the interface{} consider the code snippet below :
u, ok := myMap["user"].([]User)
if ok {
log.Printf("value = %+v\n", u)
}
Above code is simple and you can use it to check if the interface match to the type you are parsing.
And if you want to be more general passing the value to your interface{} at runtime you can check it first using reflect.TypeOf() please consider this code :
switch reflect.TypeOf(myMap["user"]).String() {
case "[]main.User":
log.Println("map = ", "slice of user")
logger.Debug("map = ", myMap["user"].([]User)[0])
case "[]main.Host":
log.Println("map = ", "slice of host")
logger.Debug("map = ", myMap["user"].([]Host)[0])
}
after you know what's the value of the interface{} you can confidently parse it the your specific data type in this case slice of user []User. Not that the main there is a package name you can change it to yours.
This is how I solved it for unstructured data. You have to parse to index string until you reach the end. Then you can print key value pairs.
yamlStr := `
input:
bind: 0.0.0.0:12002
interface: eth0
reaggregate: {}
versions: {}
output:
destination: owl-opsw-sw-dev-4.opsw:32001
interface: eth0
`
var obj map[string]interface{}
if err := yaml.Unmarshal([]byte(yamlStr), &obj); err != nil {
// Act on error
}
// Set nested object to map[string]
inputkv := streamObj["input"].(map[string]interface{})
for key, value := range inputkv {
// Each value is an interface{} type, that is type asserted as a string
fmt.Println(key, value.(string))
}
Result
bind 0.0.0.0:12002
interface eth0

Array of struct in Go language

I am new to Go and want to create and initialise an struct array in go. My code is like this
type node struct {
name string
children map[string]int
}
cities:= []node{node{}}
for i := 0; i<47 ;i++ {
cities[i].name=strconv.Itoa(i)
cities[i].children=make(map[string]int)
}
I get the following error:
panic: runtime error: index out of range
goroutine 1 [running]:
panic(0xa6800, 0xc42000a080)
Please help. TIA :)
You are initializing cities as a slice of nodes with one element (an empty node).
You can initialize it to a fixed size with cities := make([]node,47), or you could initialize it to an empty slice, and append to it:
cities := []node{}
for i := 0; i<47 ;i++ {
n := node{name: strconv.Itoa(i), children: map[string]int{}}
cities = append(cities,n)
}
I'd definitely recommend reading this article if you are a bit shaky on how slices work.
This worked for me
type node struct {
name string
children map[string]int
}
cities:=[]*node{}
city:=new(node)
city.name=strconv.Itoa(0)
city.children=make(map[string]int)
cities=append(cities,city)
for i := 1; i<47 ;i++ {
city=new(node)
city.name=strconv.Itoa(i)
city.children=make(map[string]int)
cities=append(cities,city)
}

How to Unmarshal the json array?

There is something wrong when I unmarshal the json array.
How do I correct it ? the code is:http://play.golang.org/p/AtU9q8Hlye
package main
import (
"encoding/json"
"fmt"
)
type Server struct {
ServerName string
ServerIP string
}
type Serverslice struct {
Name string
Servers []Server
}
func main() {
var s []Serverslice
str := `{"name":"dxh","servers":[{"serverName":"VPN0","serverIP":"127.0.0.1"},{"serverName":"Beijing_VPN","serverIP":"127.0.0.2"}],
"name":"dxh1,"servers":[{"serverName":"VPN1","serverIP":"127.0.0.1"},{"serverName":"Beijing_VPN","serverIP":"127.0.0.2"}]}`
json.Unmarshal([]byte(str), &s) //the wrong line.....................
fmt.Println(len(s))
}
First of all, you're ignoring the error return value from json.Unmarshal. You probably want something like:
if err := json.Unmarshal([]byte(str), &s); err != nil {
log.Fatalln(err)
}
With that change, we can see that your JSON data isn't valid: invalid character 's' after object key:value pair. There is a missing quote at the end of "dxh1 on the second line.
Fixing that error and rerunning the program you'll get a different error: json: cannot unmarshal object into Go value of type []main.Serverslice. There are two possible problems here:
You meant to decode into an object. In this case, just declare s as a Serverslice. Here is a version of your program that makes that change: http://play.golang.org/p/zgyr_vnn-_
Your JSON is supposed to be an array (possible, since it seems to have duplicate keys). Here's an updated version with the JSON changed to provide an array: http://play.golang.org/p/Wl6kUaivEm

Resources