Using count to find the last element in struct / map

Hi,
I would like feed back on this code.
I have a structure as follows:

type Host struct {
	Name    string                       `hcl:",label"`
	Default map[string]map[string]string `hcl:"default"`
	Options hcl.Body                     `hcl:",remain"`
}

and I loop through it as follows:

// cycle through hosts and display info
count := 0
last := len(f.Hosts.Default)
for _, v := range f.Hosts.Default {
    count++
    fmt.Println("{")
    fmt.Printf("  \"hostname\": \"%s\",\n", v["hostname"])
    fmt.Printf("  \"ip-address\": \"%s\",\n", v["ip-address"])
    fmt.Printf("  \"hw-address\": \"%s\"\n", v["hw-address"])
    if count == last {
        fmt.Println("}")
    } else {
        fmt.Println("},")
    }
}

Is there some go way where I do not need to use the count integer? I tried with using the key as an index but no luck as it is string and not integer.

appreciate any feedback as it is all eye opening for someone at my level of go experience.

Not conveniently. But if you are doing it multiple times, it might be worthwhile to find the last key independently and compare inside your loop(s). Of course, any operations on the map will invalidate your cached last key.

  lastKey :=  // function call that does a simple loop to find the last key.
  for k,v := range myMap {
    if k==lastKey  {...
2 Likes

Thanks for your reply. I looked into your suggestion, specifically the lastKey function and came across this…

When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next.
Go maps in action - The Go Programming Language

…therefore the last element when it is cached may not be the last element when the printing loop is run so this could have unexpected results for me, so I will stick with count for now.

…and a small question on Go styling… in the above I use count and last. Would it be more normal in the GO community to label these variables as c and l?

Sorry about the bad info. I knew iteration order was not guaranteed to be the same for the equivalent maps or the same map after changes, but I had thought that it didn’t vary on the same map without any changes on different invocations. That was probably just observed behavior which shouldn’t be relied upon, of course.

1 Like

no problem, all good info, I learnt a lot from researching the direction that you pointed me in.
that is exactly why i am here for, to learn.
thanks again