Convert from Interface to Concrete Type

What do you do when you have an object of type interface{} and want to convert it to a concrete type? You use the mysterious .(Type) operator! The following is a pretty poor example, but should get the concept across:

type Person struct {
	firstName string
	lastName  string
}

func printIfPerson(object interface{}) {
	person, ok := object.(Person)

	if ok {
		fmt.Printf("Hello %s!\n", person.firstName)
	}
}

Click here for a playground sample.

A more realistic example would be from Macaron which provides a map available in a request context that can be used to store an arbitrary data type that can be accessed later. If you added a Person at some point and wanted to access it later, you would follow the same pattern:

// ...define person

ctx.Data["person"] = person

//... some other function

person, ok := ctx.Data["person"].(Person)

if !ok {
    // error
}

//...use person

If you like to live dangerously, you don’t need to check the value of ok, but i would advise against it.

Leave a Reply

Your email address will not be published. Required fields are marked *