What is an anonymous field?

An anonymous field is a field in a struct definition that has a type but does not have a name. Below is an example of declaring an anonymous field, notice how Human struct has Animal defined but without a name.

type Animal struct {
    Name string
}

type Human struct {
    *Animal
}

Inheritance and overriding

One use case of anonymous field is to replicate the behavior of method/field inheritance and overriding in object-oriented languages. In the example below, I define a Speak() method for Animal but not for Human. However, because Human has a *Animal as an anonymous field, calling Speak() on a Human will call the Animal’s Speak method. In this case, Speak is called promoted method

//Continuing with examples above

func (a * Animal) Speak(){
    fmt.Println("Animal speaks")
}

func main() {
    a := &Animal{
        Name: "Dennis",
    }

    b := &Human{a}

    a.Speak() //Animal speaks
    b.Speak() //Animal speaks
}

We can also override Animal’s Speak method by defining a method with the same method signature for Human. Note there is no encapsulation in that we can still access Animal from Human and call its Speak method.

func (a * Animal) Speak(){
    fmt.Println("Animal speaks")
}

func (h * Human) Speak(){
    fmt.Println("Human speaks")
}

func main() {
    a := &Animal{
        Name: "Dennis",
    }
    b := &Human{a}
    a.Speak() //Animal speaks
    b.Speak() //Human speaks

    //Note here that we are still able to access Animal's Speak()
    b.Animal.Speak() //Animal speaks
}

The same logic also applies when you try accessing a field that is not explicitly defined by the containing struct (in this case Human). That is, if you try accessing Name on a Human, you are going to get Animal’s Name instead.

fmt.Println(b.Name) //Dennis

Name conflict

A struct definition can contain more than two anonymous fields and this can result in an error if not used carefully. Imagine what would happen if both anonymous fields have a field with the same name. Take a look at the example below.

type Animal struct {
    Name string
}

type Pet struct{
    Name string
}

type Human struct {
    *Animal
    *Pet
}

func main() {
    b := &Human{&Animal{Name: "Dennis"}, &Pet{Name: "Zedo"}}
    fmt.Println(b.Name); //Error
}

The above code will give you an error because calling b.Name is ambiguous and Go does not know which Name the code is referring to. You can fix the above code by being more explicit and specify the anonymous field before the selector.

//...
fmt.Println(b.Animal.Name);
fmt.Println(b.Pet.Name);
//...

Use case of anonymous methods

When writing API endpoints, you often have to parse values from the request passed in to the handler function. One easy way to do this is to create functions that would take a pointer to the request as a parameter and return the appropriate values (IP address, API version in header, etc).

func IpAddress(r * http.Request) string {
    return strings.Split(r.RemoteAddr, ":")[0]
}

func ApiVersion(r * http.Request) uint {
    //.....
}

func ValidRequest(r * http.Request) bool {
    //.....
}

A better way to do this, in my opinion, is to use anonymous field to extend the functionality of http.Request so that you can define new methods on the containing struct and still have access to http.Request methods and fields.

type APIRequest struct {
    *http.Request
}

Defining new methods for APIRequest

func (a * APIRequest) IpAddress() string{
    return strings.Split(a.RemoteAddr, ":")[0]
}

func (a * APIRequest) ApiVersion() uint{
    //logic that acts on `a`
}

func (a * APIRequest) Valid() bool{
    //logic that acts on `a`
}

And, this is how I would use APIRequest

func SessionHandler(writer http.ResponseWriter, request *http.Request ) {
    apiReq := &APIRequest{request} //Wrapping *http.Request inside APIRequest

    fmt.Println(apiReq.IpAddress()) //Using extended method

    if !apiReq.Valid() {
        //Error
    }

    fmt.Println(apiReq.Header) //Still able to access *http.Request field
}

Given all the examples above, it’s tempting to think of anonymous field as inheritance’s identical twin. However, with its minimal syntactic sugar, anonymous field provides a lot more flexibility when trying to extend behavior of a struct. One thing that I find very helpful is that, rather than thinking of anonymous field a parent-child relationship, trying thinking of it as a wrapped or decorated object.

Simple Slide Out Navigation Menu in iOS with Swift (Part 2)

Continuing from part 1, we are going to see how to switch the displayed view controller when one of the menu selections is tapped Continue reading

Subdomain with NGINX on Linode

Published on January 14, 2015