Access field in nested structures

I am having problems with something that should be simple. I am working on using the excellent cli codegangsta package, but I am trying to access a property from a nested structure and fail.

As an example, I have:

 func Something() []cli.Flag { return []cli.Flag{ cli.StringFlag{ Name: awesome Usage: "be awesome" }, cli.StringFlag{ Name: awesome2 }, <etc.> } 

I have a function that takes the returned flags []cli.Flag and tries to print the string value of Name for each member, but I cannot access the attached content in the slice. What is the right way to do this?

EDIT: Here is what I did, with Mayan add-ons a great answer

 func PrintFlagsForDriver(name string) error { for driverName := range drivers { if name == driverName { driver := drivers[driverName] flags := driver.GetCreateFlags() stringFlag, ok := flags[0].(cli.StringFlag) if ok { fmt.Println(stringFlag.Name) } } } return fmt.Errorf("Driver %s not found", name) } 

Now I get a runtime error index out of range , but I think I'm doing something else wrong.

+5
source share
2 answers

I assume you are accessing a value like this

 package main import "fmt" import "github.com/codegangsta/cli" func main() { fmt.Println("Hello, playground") a := Something() fmt.Printf("%T \n", a[0].Name) } func Something() []cli.Flag { return []cli.Flag{ cli.StringFlag{ Name: "awesome", Usage: "be awesome", }, cli.StringFlag{ Name: "awesome2", }, } } 

Which will give you the following error:

 ./main.go:10: a[0].Name undefined (type cli.Flag has no field or method Name) 

And the problem with this code is that you are accessing the values โ€‹โ€‹of struct cli.StringFlag through the cli.Flag interface. You need to introduce the conversion of this interface to the actual structure type.

We hope that the following code will make a difference.

 package main import "fmt" import "github.com/codegangsta/cli" func main() { a := Something() stringFlag, ok := a[0].(cli.StringFlag) if ok { fmt.Println(stringFlag.Name) } } func Something() []cli.Flag { return []cli.Flag{ cli.StringFlag{ Name: "awesome", Usage: "be awesome", }, cli.StringFlag{ Name: "awesome2", }, } } 
+3
source

since you are not pasting code reading the Name property, I just think you need an interface check

 if stringFlag, ok := flags[0].(cli.StringFlag); ok{ fmt.Println(stringFlag.Name) } 
0
source

All Articles